.contents()

.contents() 官网原E文: jQuery

描述: 获得每个匹配元素集合元素的子元素,包括文字和注释节点。

  • version added: 1.2.contents()

鉴于一个jQuery对象,表示一个DOM元素的集合,.contents()方法允许我们能够通过搜索这些元素和DOM树,并在他们的祖先从匹配的元素构造一个新的jQuery对象。.contents().children()方法类似,只不过前者包括文本节点以及jQuery对象中产生的HTML元素。

如果IFRAME是在与主页同域,.contents()方法也可用于获取iframe中的文件内容。

考虑一个简单<div>中一些文本节点,其中每个元素是相隔两换行符(<br /> ):

<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>

我们可以使用.contents()方法帮助转化为三合式团块为段文字:

$('.container').contents().filter(function() {
  return this.nodeType == 3;
})
  .wrap('<p></p>')
.end()
.filter('br')
  .remove();

此代码首先检索内容的<div class="container">,然后过滤它的文本节点,它被包裹在段落标记。这是通过测试元素的.nodeType属性。这个DOM属性保存一个数字代码,以显示节点的类型;文本节点使用代码3。再次过滤的内容是,这个时间<br />元素,这些元素都将被删除。

Examples:

Example: Find all the text nodes inside a paragraph and wrap them with a bold tag.

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
  <p>Hello <a href="http://ejohn.org/">John</a>, how are you doing?</p>
<script>$("p").contents().filter(function(){ return this.nodeType != 1; }).wrap("<b/>");</script>

</body>
</html>

Demo:

Example: Change the background colour of links inside of an iframe.

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
  <iframe src="http://api.jquery.com/" width="80%" height="600" id='frameDemo'></iframe> 
<script>$("#frameDemo").contents().find("a").css("background-color","#BADA55");</script>

</body>
</html>

Demo:

jQuery 1.6 API 中文版Clove整理、修订