我正在学习 javascript,但我对这段代码做错了什么感到困惑。我知道使用“替换”有更简单的方法来做到这一点,但作为学习经验,我首先尝试以困难的方式做到这一点。循环无限重复,我不知道为什么。请不要尝试按原样运行脚本,它会使您的浏览器崩溃。 :)
var text = document.getElementById("docText").innerHTML;
var textFirstChar = text.indexOf("James");
function nameReplace() {
for (var i = 0; i < text.length; i++) {
if (textFirstChar !== -1) {
text = text.slice(0, textFirstChar) +
"Albert" + text.slice(textFirstChar + 5);
}
}
}
<div id="docText">
<p>Once upon a time there was an angry horse called James the 3rd. James found it difficult to get along with other horses, mainly due to his obnoxious behaviour and wild drinking binges that could go on for days on end, usually only ending when there was no more booze left to steal from his housemates.</p>
<p>Once day, James got into a fight and was beaten to death, everyone lived happily ever after.</p>
</div>
<div id="button1">
<button onclick="nameReplace()">Replace James with Albert</button>
</div>
最佳答案
而不是你的for
循环你应该做while (textFirstChar !== -1)
并在里面重复相同的更换步骤。也不要忘记做textFirstChar = text.indexOf("James");
在循环内,替换后,它会继续搜索“James”。请注意,这是非常低效的。
关于javascript - 文本替换循环不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39557439/