现在的位置: 首页 > 综合 > 正文

jQuery html()函数

2013年11月06日 ⁄ 综合 ⁄ 共 1321字 ⁄ 字号 评论关闭

使用jQuery的html()函数获取元素内容,发现必须被<div></div>包含,否则获取的就是空

1、

var $template=$('<div><li id="mcity" data-role="list-divider"></li></div>');

console.log($tempalate.html());

//输出<li id="mcity" data-role="list-divider"></li>

2、

var $template=$('<li id="mcity" data-role="list-divider"></li>');

console.log($tempalate.html());

//输出空

查看API描述

 Get
the HTML contents of the first element in the set of matched elements.

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. Consider this code:

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

In order for the following <div>'s
content to be retrieved, it would have to be the first one with class="demo-container" in
the document:

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

The result would look like this:

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

This method uses the browser's innerHTML property.
Some browsers may not return HTML that exactly replicates the HTML source in an original document. For example, Internet Explorer sometimes leaves off the quotes around attribute values if they contain only alphanumeric characters.

但是没说没有div就空???

有人提到
.html(),.text(),
这两种用法往往用在div和span元素上,一般是为这两种元素进行赋值和取值。

.html()替代了以前的 .innerHTML , .html('test') ,则是替代了 .innerHTML = 'test';

也许是这个原因吧,有知道的告诉我,谢谢!




抱歉!评论已关闭.