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

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

问题描述

如何在文档的文本(例如cheese)中搜索某个字符串,然后在该字符串之后立即插入一些HTML(比如说,< b>是太棒了)。 / p>

我已经尝试了以下内容:

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

(以上更多的是我尝试过的例子,而不是实际的代码我希望语法是非常错误的,所以请原谅任何错误,他们不是问题)。



干杯,



Pete

解决方案

有一种在文档中查找文本的本地方法:



MSIE: textRange.findText( )

其他: window.find()



如果发现某些东西,则操作给定的textRange。

这些方法应该提供比遍历整个文档更多的性能。



示例:

 < HTML> 
< head>

< script>
函数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>奶酪< / i>来自我的< u> chees&e>电子工厂!< / p>
< / body>
< / html>


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 >").

I have tried the following:

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

Cheers,

Pete

解决方案

There are native methods for finding text inside a document:

MSIE:textRange.findText()
Others: window.find()

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

Example:

<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天全站免登陆