我正在学习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>
答案 0 :(得分:2)
代替您的for
循环,您应该执行while (textFirstChar !== -1)
并在内部重复相同的替换步骤。在替换之后也不要忘记在循环中做textFirstChar = text.indexOf("James");
,以便继续搜索&#34; James&#34;。请注意,这是非常低效的。