使用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()方法根据项/元素的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
来收紧搜索域。
相关文章:
- Javascript,有没有一种方法可以将数组写成没有逗号或空格的单个文本字符串
- 将html元素插入到文本字符串中,以匹配另一个html字符串
- 转换<a>使用jQuery将文本字符串转换为dom元素
- 数组中的随机文本字符串
- Javascript-使用“”将toDateStringMonth从文本字符串解析为数字字符串;如果“;vs“;开关”;
- javascript高亮文本字符串
- 当用户单击按钮(在光标位置)时,在输入字段中添加一个文本字符串
- 函数输入上未终止的文本字符串
- 跳过用户输入的文本字符串中的特殊字符,并在 Javascript 中的每个单词后添加连字符
- 如何使用javascript验证文本字符串
- 将部分文本字符串转换为html
- 如何使用javascript在单个正则表达式中递归替换文本字符串中重复的逗号
- 使用PowerShell在JavaScript网页上搜索文本字符串
- 使用jquery感知文本字符串中的时间范围
- 匹配最后一个点之后的文本字符串
- 从段落中删除某些文本字符串
- 如何使用 javascript 将输入到文本框中的变量插入到文本字符串中
- 当页面上存在特定文本字符串时发送 Google Analytics(分析)事件
- JSON 处理 - 向 JSP 发送 JSON 文本字符串,如何在 JSP 中处理
- 如何使用 JavaScript(但不是标签或属性)替换字符串中所有匹配的纯文本字符串