3

I am using the method below to search for a string in a web page. It matches plain text; but, it fails in the following context:

 <span>I</span> am searching for <b>text</b>

If I search for "am searching" it will match.. But if I search for "I am searching" it does not match. Below is the code I am using:

function search(text)
{
    if (document.body.createTextRange) 
    {
        var textRange = document.body.createTextRange();
        while (textRange.findText(text)) 
        {
            textRange.execCommand("BackColor", false, "yellow");
            textRange.collapse(false);
        }
    }
}

here is the fiddle. It is not working in IE8. Thanks

4

1 回答 1

1
<script type="text/javascript">
function findText(text) {
    $('*:contains('+text+')').css('background-color', 'Yellow');
});
</script>

<script type="text/javascript">
function findText(textBoxOrHtmlTagId, text) {
    $('#'+textBoxOrHtmlTagId+':contains('+text+')').css('background-color', 'Yellow');
});
$(document).ready(function(){
    $('#yourid').live('keydown', findText('yourid', $('#yourid').text());
});
</script>

应该工作:简而言之使用jquery

于 2011-12-05T22:33:32.010 回答