2016-03-19 10 views
0

JavaScriptの初心者です。.innerHTMLを使用してテキストを印刷したいのですが、動作しません。コードは次のとおりです。innerHTMLを使用してJavaScriptを使用してHTMLテーブルを更新できません

<table style="width:100%"> 
    <tr> 
     <td id="tr">&nbsp;</td> 
     <td id="tr1">&nbsp;</td> 
     <td id="tr2">&nbsp;</td> 
    </tr> 
    <tr> 
     <td id="tr3">&nbsp;</td> 
     <td id="tr4">&nbsp;</td> 
     <td id="tr5">&nbsp;</td> 
    </tr> 
    <tr> 
     <td id="tr6">&nbsp;</td> 
     <td id="tr7">&nbsp;</td> 
     <td id="tr8">&nbsp;</td> 
    </tr> 
</table> 

<script> 
document.getElementById("tr").innerHTML = "some text"; 
document.getElementById("tr2").innerHTML = "some text1"; 
document.getElementById("tr2").innerHTML = "some text2"; 
document.getElementById("tr3").innerHTML = "some text3"; 
document.getElementById("tr4").innerHTML = "some text4"; 
document.getElementById("tr5").innerHTML = "some text5"; 
document.getElementById("tr7").innerHTML = "some text6"; 
document.getElementById("tr8").innerHTML = "some text7"; 
document.getElementById("tr9").innerHTML = "some text8"; 
</script> 
+0

あなたは 'tr1'と' tr6'をスキップし、二回 'tr2'を取得しています、 d 'tr9'要素IDはありません。それとは別に、私は何の問題も見ません。 *「うまくいかない」とはどういう意味ですか? –

+0

上記のコメントに記載されている問題を修正する際に、[このフィドル](https://jsfiddle.net/v15updn1/1/)で正常に動作するようです。 – GillesC

+0

'tr1'、' tr6'を見逃していて、存在しない 'tr9'を持っていないことを除いて、あなたは'

1

は、このデモは<td>秒のNodeListを反復し、各<td>文字列を割り当てることforループを使用します。

読む:

querySelectorAll()

Loops and Iteration

NodeList

// Create an array of strings. 
 
// Each string represents what will be in each cell 
 
var content = ['row 1 col 1', 'row 1 col 2', 'row 1 col 3', 'row 2 col 1', 'row 2 col 2', 'row 2 col 3', 'row 3 col 1', 'row 3 col 2', 'row 3 col 3']; 
 

 
// Create a NodeList of every <td> with querySelectorAll() 
 
var cells = document.querySelectorAll('td'); 
 

 
//Iterate through the Nodelist (cells[]) and assign a string from the array (content[]) 
 
for (var i = 0; i < cells.length; i++) { 
 
    cells[i].innerHTML = content[i]; 
 
}
table { 
 
    border: 3px solid grey; 
 
    table-layout: fixed; 
 
    margin: 40px auto; 
 
} 
 
td { 
 
    border: 3px inset black; 
 
    outline: 2px outset grey; 
 
    height: 30px; 
 
    width: 30px; 
 
    color: blue; 
 
    padding: 5px; 
 
}
<table style="width:100%"> 
 
    <tr> 
 
    <td id="tr0">&nbsp;</td> 
 
    <td id="tr1">&nbsp;</td> 
 
    <td id="tr2">&nbsp;</td> 
 
    </tr> 
 
    <tr> 
 
    <td id="tr3">&nbsp;</td> 
 
    <td id="tr4">&nbsp;</td> 
 
    <td id="tr5">&nbsp;</td> 
 
    </tr> 
 
    <tr> 
 
    <td id="tr6">&nbsp;</td> 
 
    <td id="tr7">&nbsp;</td> 
 
    <td id="tr8">&nbsp;</td> 
 
    </tr> 
 
</table>

+0

あなたの答えは大変ありがとうございます。私は別の質問があるので、配列、ループ、および変数を条件ごとに入れなければならないのはいくつかの条件がありますか? – tom3883

+0

@ tom3883私は、あなたに合理的な答えを与えるために、それらの条件やそれらの期待などを見なければならないでしょう。しかし、*一般的には、実際にループ内に条件を持つ方が良いので、条件は変数、式の各繰り返し(フル・ループ)に適用されます。等... – zer00ne

+0

ありがとう、すべての条件にループを置き、条件に配列を入れるのが良いですか? – tom3883

関連する問題