2011-11-26 50 views
4

截至目前我使用的JavaScript搜索方法来代替身体HTML像下面一些文字..什么是最好的方法来搜索正文的HTML一些文字

假设我的HTML是

<body> 
     <div> I am in body...</div> 
</body> 

然后我使用下面的方法

var body = $(body); 
var text = body.html(); 
text = text.replace('I am in body...','Yes'); 
body.html(text); 

但我可以看到像IE浏览器慢页面搜索..
请给我建议,以提高日是,也请让知道是否有任何插件,以搜索和匹配,即使它包含在任何HTML标记的字符串。像下面

<body> 
     <div><span>I </span> am in body...</div> 
</body> 

当前的方法我无法比拟的..
如果我使用

$('*:contains("some search text string")'); 

这将匹配DIV和BODY以及..但在这里我想搜索的HTML文本没有父元素...... 感谢

回答

3

你应该看看:

范围:(修改文本,而不会覆盖整个身体)

IE:http://msdn.microsoft.com/en-us/library/ms535872%28v=vs.85%29.aspx
其他:https://developer.mozilla.org/en/DOM/range


查找()/ FINDTEXT()(创建范围)

IE:http://msdn.microsoft.com/en-us/library/ms536422%28v=vs.85%29.aspx
其他:https://developer.mozilla.org/en/DOM/window.find

(Opera不支持查找或FINDTEXT)


对此question小修改:

<html> 
<head> 

    <script> 
    function fx(a,b) 
    { 
    if(window.find) 
    { 
     while(window.find(a)) 
     { 

     var rng=window.getSelection().getRangeAt(0); 
     rng.deleteContents(); 

     rng.insertNode(document.createTextNode(b)); 

     } 
    } 
    else if(document.body.createTextRange) 
    { 
     var rng=document.body.createTextRange(); 
     while(rng.findText(a)) 
     { 
     rng.pasteHTML(b); 
     } 
    } 
    } 
    </script> 
</head> 
<body onload="fx('I am in body...','Yes')"> 
<div>Oh <span>I </span>am in body...<i>, wonderful</i></div> 
</body> 
</html> 
+0

@ dr-molle非常非常感谢...我从长期寻找这个解决方案..你做我的日子 – Exception

+0

@ dr-molle你可以看看这个... http://jsfiddle.net/3gPbh/ ..请告诉我的代码中的错误.. – Exception

+0

你没有通过预期的参数,电话有'fx('我在身体...','是')' –

0

试试这个:

 
$(function() { 
    var foundin = $('body:contains("some search text string")'); 
}); 

希望它可以帮助

+0

我可以用$( '*:包含( “某些搜索文本字符串”)');但我只是想搜索字符串不是父母..此外,这将符合父母的标签和身体标签.. – Exception

1

你会得到只包含完整的文本元素
没有为人父母的一些其他元素包含相同的文本

var str = "some search text string"; 
var elements = $("*:contains('"+ str +"')").filter(
        function(){ 
         return $(this).find("*:contains('"+ str +"')").length == 0 
        } 
       ); 
1

我觉得你的代码工作得很好,但你的错误是你没有弄清楚“身体”的内容。

这里是你的代码:

$(document).ready(function(){ 
    var body = $("body"); // your miss this 
    var text = body.html(); 
    text = text.replace('I am in body...','Yes'); 
    body.html(text); 
}); 
相关问题