-1

I want to highlight a word within a div when page will be loaded. My code is

<script type="text/javascript">
function highlight(container,what,spanClass) {
    var content = container.innerHTML,
        pattern = new RegExp('(>[^<.]*)(' + what + ')([^<.]*)','g'),
        replaceWith = '$1<span ' + ( spanClass ? 'class="' + spanClass + '"' : '' ) + '">$2</span>$3',
        highlighted = content.replace(pattern,replaceWith);
    return (container.innerHTML = highlighted) !== content;
}
</script>
</head>

<body onload="highlight(document.getElementById('hello'),'florida','highlight');">
<div id="hello"> Florida florida orlando orlando</div>
Florida Texus florida 
</body>

</html>

And nothing is happening in FF/Chrome/IE. I need your advice to fix this.

4

2 回答 2

1

那是因为您使用的此代码仅在您的元素周围有一些 HTML 标记时才有效。

它适用于更一般的情况,例如,如果您将 div 更改为

<div id="hello"><p> Florida florida orlando orlanodo</p></div>

要使其与您的 HTML 一起使用,您可以使用更简单的正则表达式:

new RegExp('(' + what + ')','g')

和不同的替代品:

replaceWith = '<span ' + ( spanClass ? 'class="' + spanClass + '"' : '' ) + '">$1</span>'

您也可以刚刚更改您的正则表达式以使组可选:

pattern = new RegExp('(>[^<.]*)?(' + what + ')([^<.]*)?','g'),

示范

于 2013-07-01T08:12:10.457 回答
1

我认为您正在寻找的是突出显示单词florida,如果它是分开的,然后尝试

function highlight(container,what,spanClass) {
    var content = container.innerHTML,
        pattern = new RegExp('\\b(' + what + ')\\b','g'),
        replaceWith = '<span ' + ( spanClass ? 'class="' + spanClass + '"' : '' ) + '">$1</span>',
        highlighted = content.replace(pattern,replaceWith);

    return (container.innerHTML = highlighted) !== content;
}

演示:小提琴

于 2013-07-01T08:13:56.507 回答