簡體   English   中英

使用getElementById突出顯示頁面上的文本字符串

[英]Highlighting text strings on page using getElementById

我是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獲取@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>'); 
}

這里不需要正則表達式。 您可以使用element.innerHTML替換body.innerHTML來收緊搜索域。

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插件來完成這項工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM