使用getElementById突出显示页面上的文本字符串

Highlighting text strings on page using getElementById

本文关键字:文本 字符串 getElementById 显示 使用      更新时间:2023-09-26

我是JavaScript新手。我正面临着一个问题与我的javascript代码。我试图使用字符串替换方法来突出显示搜索的文本。但这行不通。我一定是弄错了。或许我用错了方法。请帮助。下面是我的代码:

<html><head>
<style>span.red { color:red; }</style>
<script language="javascript">
function highlightText(htext) {
    var str = document.getElementById(htext).value;
    //highlight the searched text
    str.replace(/(['w]+)/g, '<span class="red">$1</span>'); 
}
</script></head>
<body><span>Enter a word to search in the paragraph below:</span></br>
<input type="text" id="text-to-find" />
<button onClick="highlightText('text-to-find');">Find</button><hr/><hr/>
<p><b>Type any word from this paragraph in the box above, then click the "Find" button to highlight it red.</b></p></body></html>

getElementById()方法根据项/元素的id而不是指定的字符串值查找项/元素。

这是你的固定代码,它做你需要它…如果你要在一个真实的项目/网站中使用它,你可能想要改进它。

<html><head>
<style>span.red { color:red; }</style>
<script language="javascript">
function highlightText(htext){
    var str = document.getElementById("sometext").innerHTML;
    str = str.replace(htext, '<span style="background-color:red;">' + htext + '</span>'); 
    document.getElementById("sometext").innerHTML = str;    
}
</script></head>
<body><span>Enter a word to search in the paragraph below:</span></br>
<input type="text" id="text-to-find" />
<button onClick="highlightText(document.getElementById('text-to-find').value);">Find</button><hr/><hr/>
<p id="sometext">
<b>Type any word from this paragraph in the box above, then click the "Find" button to highlight it red.</b></p></body></html>

或者,您可以使用这个jQuery插件来完成这项工作。

当我看到你的代码时,我想到的第一件事是你试图使用getElementById来获得@Joel猜测的文本部分。但后来,我意识到您使用它来获取对保存要替换的文本的输入框的引用。这是完全正确的。

然而,你似乎对正则表达式和string.replace方法的概念有一点误解。

似乎你假设它是text_to_be_found.replace(some_regexp, substitute)不是正确。它是:haystack.replace(needle_which_can_be_regexp, substitute),并且由于字符串是不可变的,它在替换后返回新字符串。

你应该这样做:

function highlightText(htext)
{
    var str = document.getElementById(htext).value;
    //highlight the searched text
    body.innerHTML = body.innerHTML.replace(str, '<span class="red">' + str + '</span>'); 
}

这里不需要正则表达式。您可以将body.innerHTML替换为element.innerHTML来收紧搜索域。