【问题标题】:Highlighting text strings on page using getElementById使用 getElementById 在页面上突出显示文本字符串
【发布时间】:2011-12-04 18:32:52
【问题描述】:

我是 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>

【问题讨论】:

  • 在函数末尾添加document.getElementById(htext).value = str。您还可以将document.getElementById... 存储在变量中以稍微提高性能。
  • @RobW 感谢您的回复。我照您说的做了。但是还是不行
  • 因为您不能在输入字段中包含 HTML。您必须创建一个容器,例如&lt;span&gt;&lt;/div&gt;,并将其放置在元素上。要找出字符的位置,请使用this answer 中提供的代码。

标签: javascript


【解决方案1】:

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>

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

【讨论】:

  • 没问题。很高兴它帮助了你:)
【解决方案2】:

当我查看您的代码时,我首先想到的是您正在尝试使用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 以收紧搜索域。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-01
    • 2017-04-04
    • 1970-01-01
    • 2016-06-28
    • 2013-12-17
    • 1970-01-01
    • 1970-01-01
    • 2019-09-13
    相关资源
    最近更新 更多