$("p").contents().filter(function(){ return this.nodeType != 1; }).wrap("<b/>");
詳細(xì)說(shuō)明.contents()
我們可以使用 .contents() 方法來(lái)把文本塊轉(zhuǎn)換為形式良好的段落:<div class="container">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed
do eiusmod tempor incididunt ut labore et dolore magna aliqua.
<br /><br />
Ut enim ad minim veniam, quis nostrud exercitation ullamco
laboris nisi ut aliquip ex ea commodo consequat.
<br /> <br />
Duis aute irure dolor in reprehenderit in voluptate velit
esse cillum dolore eu fugiat nulla pariatur.
</div>
$('.container').contents().filter(function() {
return this.nodeType == 3;
})
.wrap('<p></p>')
.end()
.filter('br')
.remove();
以下jQuery示例代碼用于演示contents()函數(shù)的具體用法:<p id="n1">
Hello
<span id="n2">
CodePlayer
<span id="n3">A</span>
</span>
<!-- 注釋內(nèi)容 -->
<span id="n4">
B
<label id="n5"></label>
</span>
</p>
//返回jQuery對(duì)象所有匹配元素的標(biāo)識(shí)信息數(shù)組
//每個(gè)元素形如:[文本內(nèi)容]、[--注釋內(nèi)容--]或#id
function getTagsInfo($doms){
return $doms.map(function(){
if(this.nodeType == 3){ // 文本節(jié)點(diǎn)
return "[" + this.nodeValue + "]";
}else if(this.nodeType == 8){ // 注釋節(jié)點(diǎn)
return "[--" + this.nodeValue + "--]";
}else{
return "#" + this.id;
}
}).get();
}
// 匹配n1元素所有的子節(jié)點(diǎn)(包括文本節(jié)點(diǎn)、注釋節(jié)點(diǎn)等,下同)
var $n1_contents = $("#n1").contents();
document.writeln( getTagsInfo( $n1_contents ) ); // [ Hello ],#n2,[ ],[-- 注釋內(nèi)容 --],[ ],#n4,[ ]
//匹配span元素所有的子節(jié)點(diǎn)
var $span_contents = $("span").contents();
document.writeln( getTagsInfo( $span_contents ) ); // [ CodePlayer ],#n3,[ ],[A],[ B ],#n5,[ ]
// 匹配span元素所有子節(jié)點(diǎn)中的非Element節(jié)點(diǎn)
var $span_text = $span_contents.filter( function(){
return this.nodeType != 1;
} );
document.writeln( getTagsInfo( $span_text ) ); // [ CodePlayer ],[ ],[A],[ B ],[ ]
//匹配n5元素所有的子節(jié)點(diǎn),n5標(biāo)簽中沒(méi)有任何內(nèi)容,因此返回空的jQuery對(duì)象,匹配0個(gè)元素
var $n5_contents = $("#n5").contents();
document.writeln( $n5_contents.length ); // 0
語(yǔ)法結(jié)構(gòu):
$(selector).contents()
實(shí)例代碼:
<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <meta name="author" content="http://theartemis.cn/" /> <title>contents()函數(shù)-365建站網(wǎng)</title> <script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("ul").contents().not("[nodeType==1]").css("color","red"); }) </script> </head> <body> <div> <ul> <li>html專區(qū)</li> <li>DIV+CSS專區(qū)</li> <li>Javascript專區(qū)</li> <li>Jquery專區(qū)</li> </ul> </div> </body> </html>
以上代碼可以將ul元素下的文本節(jié)點(diǎn)的顏色設(shè)置為紅色。
jquery的contents()訪求可以獲取iframe里面的元素,如
<iframe id="test" src="test.jsp"></iframe>
$("#test").contents().find("#testI");這句話的作用就是能夠得到test.jsp里面的id為testI的節(jié)點(diǎn)
如對(duì)本文有疑問(wèn),請(qǐng)?zhí)峤坏浇涣髡搲?,廣大熱心網(wǎng)友會(huì)為你解答?。?點(diǎn)擊進(jìn)入論壇