使用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描述
-
html()
- .html()
-
html(
htmlString )
- .html( htmlString )
- .html( function(index, oldhtml) )
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.
有人提到
.html(),.text(),這兩種用法往往用在div和span元素上,一般是爲這兩種元素進行賦值和取值。
.html()替代了以前的 .innerHTML , .html('test') ,則是替代了 .innerHTML = 'test';
也許是這個原因吧,有知道的告訴我,謝謝!