JQuery中的html()方法

来源:互联网 发布:中国金融软件 编辑:程序博客网 时间:2024/05/17 02:32

jquery中html方法


html()方法

This method is not available on XML documents.

In an HTML document, .html() can be used to get the contents of any element. If the selector expression matches more than one element, only the first match will have its HTML content returned.


概述:取得第一个匹配元素的html内容。要注意的是该函数不能用于XML文档。

在一个 HTML 文档中, 我们可以使用 .html() 方法来获取任意一个元素的内容。 如果选择器匹配多于一个的元素,那么只有第一个匹配元素的 HTML 内容会被获取。

<div class="demo-container">  <div class="demo-box">Demonstration Box</div></div>


则如下代码的返回结果为<div class="demo-box">Demonstration Box</div>

$( "div.demo-container" ).html();


此方法相当于JS中的 innerHTML 方法。同样,该方法也可用来设置指定DOM元素的HTML内容,如下

html( htmlString )方法

Description: Set the HTML contents of each element in the set of matched elements.

例如设置所有 p 元素的内容为Hello world!

$("p").html("Hello world!");


在jQuery1.4版本允许使用函数来设置所有匹配元素的内容

html( function ) 例如:

<div class="demo-container">  <p>All new content. <em>You bet!</em></p></div>$( "div.demo-container" ).html(function() {  var emphasis = "<em>" + $( "p" ).length + " paragraphs!</em>";  return "<p>All new content for " + emphasis + "</p>";});


这里要区分出html()方法和append()方法:html()方法用来设置对应HTML元素内容或者说成替换,而append()方法用来追加内容。

还要区分出和val()方法的区别

The .val() method is primarily used to get the values of form elements such as input, select and textarea. When called on an empty collection, it returns undefined.

即val()方法只能用于表单元素,例如input,select标签。