本节书摘来自异步社区《jQuery、jQuery UI及jQuery Mobile技巧与示例》一书中的第3章,第3.5节,作者:【荷】Adriaan de Jonge , 【美】Phil Dutson著,更多章节内容可以访问云栖社区“异步社区”公众号查看
3.5 技巧:更改元素的HTML内容
为了能方便地操作HTML元素的innerHTML属性,jQuery提供了html()方法。代码清单3-5演示了它的用法。
代码清单3-5 选取一个段落元素并替换它的HTML内容
00 <!DOCTYPE html>
01
02 <html lang="en">
03 <head>
04 <title>The html() function</title>
05 </head>
06 <body>
07
08 <h2>Press the button to see the old HTML in the
09 paragraph and replace it with new HTML</h2>
10
11 <p>This <strong>contains</strong> some
12 <a href="http://www.w3.org/TR/html5/">HTML</a>
13 of its <em>own</em>.</p>
14
15 <button>Change</button>
16
17 <script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
18
19 <script>
20 // 请将下列代码移至一个外部的.js文件中
21 $(document).ready(function() {
22
23 $('button').click(function() {
24
25 var p = $('p');
26
27 alert('The old HTML was:\n' + p.html());
28
29 p.html('<p>And that can be replaced with ' +
30 '<em>simple</em> new HTML.</p>');
31
32 });
33
34 });
35 </script>
36 </body>
37 </html>
可以直接把HTML字符串传给html(),也可以传包含HTML的jQuery对象。html()较之innerHTML的主要好处是它可以直接操作jQuery选取集,而不用先把它转换成数组1。