0
点赞
收藏
分享

微信扫一扫

jQuery中.contents()使用方法

在 jQuery 中,.contents() 方法用于获取匹配元素集合中每个元素的所有子节点(包括文本节点、注释节点和元素节点)。它常用于操作 iframe 内容、提取纯文本或处理包含混合节点的 DOM 结构。

一、基本语法

$(selector).contents()

  • 返回值:jQuery 对象,包含所有子节点(包括文本节点、注释节点等)。
  • 注意:与 .children() 不同,.children() 只返回元素节点,而 .contents() 返回所有类型的子节点。

二、常见用途

1. 获取 iframe 的文档内容

这是 .contents() 最常见的用法之一:

<iframe id="myFrame" src="page.html"></iframe>

$('#myFrame').on('load', function() {
    var iframeDoc = $(this).contents();
    var title = iframeDoc.find('title').text();
    console.log('Iframe title:', title);
});

注意:只有当 iframe 与主页面同源(same-origin)时才能访问其内容,否则会因跨域限制报错。

2. 获取包含文本节点在内的所有子节点

<div id="example">
    Hello <!-- 这是一个注释 -->
    <span>World</span>
</div>

var nodes = $('#example').contents();
nodes.each(function(index, node) {
    console.log('Node type:', node.nodeType, 'Content:', node.nodeValue || node.innerHTML);
});

输出可能为:

Node type: 3 Content: Hello 
Node type: 8 Content:  这是一个注释 
Node type: 1 Content: <span>World</span>

  • nodeType === 3:文本节点
  • nodeType === 8:注释节点
  • nodeType === 1:元素节点

3. 修改第一个文本节点的内容

$('#example').contents().filter(function() {
    return this.nodeType === 3; // 文本节点
}).first().replaceWith('Hi ');

执行后 HTML 变为:

<div id="example">
    Hi <!-- 这是一个注释 -->
    <span>World</span>
</div>

三、注意事项

  • .contents() 包含所有子节点,包括空白文本节点(如换行、缩进),使用时需注意过滤。
  • 在处理跨域 iframe 时,浏览器安全策略会阻止访问 .contents(),导致错误。
  • 如果用于 <iframe>,必须确保 iframe 已加载完成(使用 load 事件)。

四、完整代码

<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>

<div id="container">
  Start
  <p>Paragraph</p>
  End
</div>

<iframe id="frame" src="about:blank"></iframe>

<script>
  // 示例1:遍历所有子节点
  $('#container').contents().each(function() {
    if (this.nodeType === 3) {
      console.log('Text node:', this.nodeValue.trim());
    } else if (this.nodeType === 1) {
      console.log('Element:', this.tagName);
    }
  });

  // 示例2:动态写入 iframe 并读取
  const iframe = document.getElementById('frame');
  const doc = iframe.contentDocument || iframe.contentWindow.document;
  doc.open();
  doc.write('<html><head><title>Test</title></head><body><h1>Hello from iframe</h1></body></html>');
  doc.close();

  $('#frame').on('load', function() {
    const h1Text = $(this).contents().find('h1').text();
    alert('Iframe says: ' + h1Text);
  });
</script>

</body>
</html>

举报

相关推荐

0 条评论