0

私はJavaScriptの初心者ですが、次の問題を理解できません。ユーザーがプレーヤーの名前を入力できるようにする簡単なJavaScriptゲームを作成しようとしています。

私はこれを「for」ループで解決しようとしました。これは、たとえば5回繰り返されます(ユーザーの以前の選択による)。ただし、ユーザーがプレーヤーの名前を入力できるようにする次のコードをループしようとすると、常にnrから始まります。4で、ループしなくなりますが、代わりに終了します。どうしてこんなことに?コードを改善して機能させるにはどうすればよいですか?

for (var i=0; i<5;i++){
    document.getElementById('content').innerHTML = '<form name=players_name><p>Name of the player '+
                                                   i+
                                                   '</p><input type="text" name="player_name"></br><input type="button" value="Submit" onclick="somefunction()"></form>';
}

どうもありがとう

4

4 に答える 4

0

ここに画像の説明を入力してください

var content = "";                                          //create "content"
for (var i=0; i<5;i++){
    content += '...'+i+'...'+"<br>";                       //Add your HTML inside
}                                                          //¯¯¯
document.getElementById('content').innerHTML = content;    //Put it into DOM

これにより、innerHTMLが毎回上書きされないようになります。

于 2012-12-30T19:13:20.787 に答える
0

演算子を使用して+=、各反復でHTMLを追加します。

document.getElementById('content').innerHTML += "...";

ただし、これを行うとパフォーマンスが低下します。むしろ、配列を使用して文字列を収集し、ループの最後の要素に配置します。

for (var i = 0, html = []; i < 5; i++) {
    html.push( '..' );
}

document.getElementById('content') = html.join();
于 2012-12-30T19:08:13.013 に答える
0

Try using alert() or console.log() to see if it's actually your loop, or, if it's your code within the loop's body.

for (var i=0; i<5;i++){
alert(i);
document.getElementById('content').innerHTML = '<form name=players_name><p>Name of the player '+i+'</p><input type="text" name="player_name"></br><input type="button" value="Submit" onclick="somefunction()"></form>';
}

This will show you a message box with your variable i's value with each iteration.

You can also use

console.log(i);

with your browser's debug console (be warned, this has some compatibility issues with IE < 8)

于 2012-12-30T19:10:13.457 に答える
0

Your code has a mistake. You overwrite 4 times the content of the HTML element with id "content". So there is the answer, why did you see just the fourth form.

Here is the fixed code:

// Make a variable what will contain the forms
var content_output = "";

for (var i=0; i<5;i++){
     content_output += '<form name=players_name><p>Name of the player ' + i + '</p><input type="text" name="player_name"></br><input type="button" value="Submit" onclick="somefunction()"></form>';
}

// Add the content_output variable's content to the HTML element width 'content' id
document.getElementById('content').innerHTML = content_output;
于 2012-12-30T19:21:37.253 に答える