2016-09-18 86 views
0

我正在学习JavaScript的过程中,我被卡在我做错了这段代码。我知道有更简单的方法来使用'替换'来做到这一点,但我试图首先作为一种学习体验来做到这一点。循环无限重复,我不知道为什么。请不要尝试按原样运行脚本,否则会导致浏览器崩溃。 :)文本替换循环不工作

var text = document.getElementById("docText").innerHTML; 
 
var textFirstChar = text.indexOf("James"); 
 
\t 
 
function nameReplace() { 
 
\t for (var i = 0; i < text.length; i++) { 
 
\t \t if (textFirstChar !== -1) { 
 
\t \t \t text = text.slice(0, textFirstChar) + 
 
\t \t \t "Albert" + text.slice(textFirstChar + 5); 
 
\t \t } 
 
\t } 
 
}
<div id="docText"> 
 
\t <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>

回答

2

for循环,而不是你应该做while (textFirstChar !== -1)和重复内相同的替换步骤。也不要忘记在循环内部做textFirstChar = text.indexOf("James");,在替换之后继续搜索“James”。请注意,这是非常低效的。

+0

谢谢,我知道我错过了一些明显的东西。我也没有发表声明去实际取代我现在所做的文字。非常感谢! :) – Cuckoo

+0

没问题,很高兴我可以帮助:) –