【发布时间】: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。您必须创建一个容器,例如
<span>或</div>,并将其放置在元素上。要找出字符的位置,请使用this answer 中提供的代码。
标签: javascript