【发布时间】:2015-04-03 22:49:20
【问题描述】:
我有一个带有一些文字的 textarea(假设它说 THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG)。当我按下一个按钮时,textarea 的内容会发生变化,将单词“BROWN”替换为另一个单词(例如“RED”)
<textarea id="text3" >THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG.</textarea>
<input type="button" value="Click here" onclick="myFunction();"/>
<script type="application/javascript">
function myFunction() {
var textElem = document.getElementById("text3");
var newText = textElem.replace("BROWN", "RED");
newText = textElem.replace("FOX", "RABBIT");
newText = textElem.replace("JUMPED", "LEAPED");
newText = textElem.replace("LAZY", "SLEEPING");
textElem.value = newText.value;
}
</script>
代码似乎不起作用。我尝试查看函数是否正确调用以及变量是否为字符串。
编辑: 该函数现在显示为:
function myFunction() {
var textElem = document.getElementById("text3").value;
newText = textElem.replace("BROWN", "RED");
newText = textElem.replace("FOX", "RABBIT");
newText = textElem.replace("JUMPED", "LEAPED");
newText = textElem.replace("LAZY", "SLEEPING");
alert(newText); /*I added this to see what the value of newText is*/
textElem = newText;
}
通过警报,我注意到 newText 与原始文本没有任何变化。 textElem.replace 有什么问题吗?
【问题讨论】:
-
改用这个:var textElem = document.getElementById("text3").value;
-
您使用的是元素本身而不是其中的文本。使用
var textElem = document.getElementById("text3").value;。
标签: javascript html string replace