JQuery/Javascript - 在 DOM 中搜索文本并插入 HTML [英] JQuery/Javascript - Search DOM for text and insert HTML

查看:23
本文介绍了JQuery/Javascript - 在 DOM 中搜索文本并插入 HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何在 DOM 中搜索文档文本中的某个字符串(例如,cheese"),然后在该字符串之后立即插入一些 HTML(例如,< b >is wonderful</b >").

How do I search the DOM for a certain string in the document's text (say, "cheese") then insert some HTML immediately after that string (say, "< b >is fantastic< /b >").

我尝试了以下方法:

for (var tag in document.innerHTML) {
    if (tag.matches(/cheese/) != undefined) {
        document.innerHTML.append(<b>is fantastic</b>
    }
}

(以上更多是我尝试过的说明,而不是实际代码.我认为语法非常错误,所以请原谅任何错误,它们不是问题).

(The above is more of an illustration of what I have tried, not the actual code. I expect the syntax is horribly wrong so please excuse any errors, they are not the problem).

干杯,

皮特

推荐答案

有一些本地方法可以在文档中查找文本:

There are native methods for finding text inside a document:

MSIE:textRange.findText()
其他:window.find()

如果发现某些内容,则操作给定的 textRange.
这些方法应该比遍历整个文档提供更多的性能.

Manipulate the given textRange if something was found.
Those methods should provide much more performance than the traversing of the whole document.

例子:

<html>
<head>

  <script>
  function fx(a,b)
  {
    if(window.find)
    {
      while(window.find(a))
      {
        var node=document.createElement('b');
            node.appendChild(document.createTextNode(b));
        var rng=window.getSelection().getRangeAt(0);
            rng.collapse(false);
            rng.insertNode(node);
      }
    }
    else if(document.body.createTextRange)
    {
      var rng=document.body.createTextRange();
      while(rng.findText(a))
      {
        rng.collapse(false);
        rng.pasteHTML('<b>'+b+'</b>');
      }
    }
  }
  </script>
</head>
<body onload="fx('cheese','is wonderful')">
<p>I've made a wonderful cheesecake with some <i>cheese</i> from my <u>chees</u>e-factory!</p>
</body>
</html>

这篇关于JQuery/Javascript - 在 DOM 中搜索文本并插入 HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆