使用javascript在文本中插入链接而不替换div的整个内容

2024-04-23

我正在编写一个小部件,用于在指定的“#content”div 中搜索特定关键字。

以下是我最初使用 jQuery(简化版)进行设置的方法:

  • 设置一个等于内容 html 的变量:var content = $('content').html();
  • 使用一些正则表达式来替换某些关键字<a href='link.html'>keyword</a>
  • 将内容 div 的 html 替换为新内容:$('content').html(content);

这在大多数情况下都有效,但是当“#content”div 包含 javascript 时就会出现问题。当我设置$('content').html(content),它重新运行包含在$('content')div,这可能会导致错误。由于这是我编写的可以在任何网站上使用的小部件,因此我无法控制内容 div 以及其中是否有任何 javascript。

我的问题是,有没有办法将关键字替换为<a href='link.html'>keyword</a>,而不替换 div 的整个内容?


我的问题是,有没有办法将关键字替换为<a href='link.html'>keyword</a>,而不替换 div 的整个内容?

是的。这是 jQuery 没有真正为您提供太多功能的(少数)地方之一。

不过,在原始 DOM API 级别,Text node http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-1312295772包含元素的实际文本有一个splitText功能 http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-38853C1D您可以使用它在特定位置将节点拆分为两个相邻节点。因此,在您的情况下,您将在单词的开头处拆分,然后在单词结尾处再次拆分,然后将中间的部分换行Text新锚点中的节点。

这是一个例子:实时复制 http://jsbin.com/afiwun | source http://jsbin.com/afiwun/edit

HTML:

<input type="button" id="theButton" value="Make it a link">
<p id="example">This is the example paragraph.</p>

JavaScript:

jQuery(function($) {

  $("#theButton").click(function() {
    var targetWord, p, textNode, index, nodeWord, nodeAfter;

    // Our target word
    targetWord = "example";

    // Get the paragraph using jQuery; note that after we
    // use jQuery to get it (because it fixes getElementById for
    // us on older versions of IE), we then use [0] to access
    // the *raw* `p` element.
    // Then get the text node from it.
    p = $("#example")[0];
    textNode = p.firstChild;

    // Find our text in the text node
    index = textNode.nodeValue.indexOf(targetWord);
    if (index !== -1) {
      // Split at the beginning of the text
      nodeWord = textNode.splitText(index);

      // Split the new node again at the end of the word
      nodeAfter = nodeWord.splitText(targetWord.length);

      // Insert a new anchor in front of the word
      anchor = document.createElement('a');
      anchor.href = "http://stackoverflow.com";
      p.insertBefore(anchor, nodeWord);

      // Now move the word *into* the anchor
      anchor.appendChild(nodeWord);
    }
  });

});

当然,您需要做一些事情来改进:

  • 处理index === 0情况下,无需在父元素的开头创建空文本节点。(无害,但不太理想。)
  • 处理单词位于最前面的情况end父级的文本节点,因此最终不会出现空文本节点。(Again.)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用javascript在文本中插入链接而不替换div的整个内容 的相关文章