0
私はJavaScriptを学ぶ過程にあり、私はこのコードで何が間違っているのか悩んでいます。私はこれを行うための簡単な方法があることを知っている '交換'を使用して、私はそれを学習の経験としてまず難しい方法をしようとしています。ループは無限に繰り返されていますが、なぜその理由がわかりません。スクリプトをそのまま実行しようとしないでください。ブラウザがクラッシュします。 :)あなたfor
ループの代わりにテキストの置換ループが機能しない
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>
ありがとうございます、私は明らかなものが欠けていることを知っていました。私はまた、今行っているテキストを実際に置き換えるための声明を出していませんでした。どうもありがとう! :) – Cuckoo
いいえ問題は、うれしい私が助けることができる:) –