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

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

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

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

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

我的问题是,有没有办法用keyword替换keyword ,而无需替换div的整个内容?

我的问题是,有没有办法用keyword替换keyword ,而无需替换div的整个内容?

是。 它是jQuery并不能为你提供太多function的少数几个地方之一。

但是,在原始DOM API级别下,包含元素实际文本的Text节点具有splitText函数 ,您可以使用该函数将节点拆分为特定位置的两个相邻节点。 因此,在您的情况下,您将在单词的开头拆分,然后在结束之后再拆分,然后将该中间Text节点包装在新锚中。

这是一个例子: 实时复制 | 资源

HTML:

  

This is the example paragraph.

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大小写而不在父元素的开头创建空文本节点。 (无害,但不太理想。)
  • 处理单词位于父对象末尾的情况,因此您不会在那里结束空文本节点。 (再次。)

你可以只替换关键字而不替换像这样的所有内容,

 function keywordconvert(str, p1, offset, s) { return ""+p1+""; } function search(keyword) { var content = document.getElementById("content"); var re = new RegExp("("+keyword+")","g"); content.innerHTML = content.innerHTML.replace(re, keywordconvert); } 

用法

 search("keyword"); 

DEMO

是的,但您必须手动遍历所有文本节点。

首先去除标签要容易得多,因为一旦它们被运行,它们就不需要在页面上(一切都保存在内存中)。

 $('#content script').remove(); 

这将从#content元素中删除脚本,然后您可以毫无问题地运行现有的替换代码。