如果文本中有任何格式,为什么这个函数会失败?(在IE8)

Why does this function fail if there is any formatting in the text? [in IE8]

本文关键字:失败 函数 IE8 文本 任何 格式 为什么 如果      更新时间:2023-09-26

我使用下面的方法来搜索网页中的字符串。它匹配纯文本;但是,它在以下上下文中失败:

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

如果我搜索"am searching",它将匹配…但是如果我搜索"我正在搜索",它是不匹配的。下面是我使用的代码:

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

这是小提琴。它不能在IE8中工作。由于

<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