1

ユーザーが色を入力するページがあり、onClick メソッドを呼び出してテーブルの個々のセルの色を変更します。ただし、任意のセルをクリックすると、最後のセル (この場合は cell3) だけが色が変わります。私は何を間違っていますか?

エラーが発生します:

メッセージ: 'document.getElementById(...)' は null またはオブジェクトではありません
行: 24
文字: 4
コード: 0

私のコードは次のとおりです。

    <html>

    <body>
    <input type='text' id='userInput' value='yellow' />

    <table border="1"> 
        <tr>
            <td id="1">cell1
            </td>
        </tr>
        <tr>
            <td id="2">cell2
            </td>
        </tr>
        <tr>
            <td id="3">cell3
            </td>
        </tr>

    </table>

    <script type="text/javascript">
    for(var i = 1; i <= 3; i++){
        document.getElementById(i).onclick = function(){
        var newColor = document.getElementById('userInput').value;
            document.getElementById(i).style.backgroundColor = newColor;
        }
    }
    </script> 
    </body>

    </html>
4

3 に答える 3

3

HTMLを次のように変更します。IDは英字で始まる必要があります。数字で始めることは無効です。

<table border="1"> 
    <tr>
        <td id="td1">cell1
        </td>
    </tr>
    <tr>
        <td id="td2">cell2
        </td>
    </tr>
    <tr>
        <td id="td3">cell3
        </td>
    </tr>

</table>

これは非常に一般的なJavascriptの問題です。すべてのコードは、ループの最後にiある値を共有します。3次のような別のヘルパー関数を使用して解決できます。

function changeIt(i) {
  // This inner function now has its own private copy of 'i'
  return function() {
    var newColor = document.getElementById('userInput').value;
      document.getElementById("td" + i).style.backgroundColor = newColor;
  }
}

for(var i = 1; i <= 3; i++){
    document.getElementById(i).onclick = changeIt(i);
}

匿名関数を使用して作成することもできますが、それらは読みにくいです。

于 2012-09-20T08:26:11.593 に答える
1

ジェレミーの答えは近いですが、要素がクリックされるまで changeIt が呼び出されず、i の値がまだ 3 であることにはまだ問題があります。Jeremy の HTML への更新を使用すると、正しいスクリプトは次のように記述できます...

function createChangeColorHandler(n) {
  return function() {
    var newColor = document.getElementById('userInput').value;
    document.getElementById("td" + n).style.backgroundColor = newColor;
  }
}

for(var i = 1; i <= 3; i++) {
  // We pass i to the function createChangeColorHandler by value
  // at the time of this pass of the loop rather than referencing 
  // the variable directly after the loop has finished
  document.getElementById(i).onclick = createChangeColorHandler(i);
}

無名関数として...

for(var i = 1; i <= 3; i++) {
  // We pass i to the function createChangeColorHandler by value
  // at the time of this pass of the loop rather than referencing 
  // the variable directly after the loop has finished
  document.getElementById(i).onclick = (function(n) {
    return function() {
      var newColor = document.getElementById('userInput').value;
      document.getElementById("td" + n).style.backgroundColor = newColor;
    }
  })(i);
}

編集ジェレミーの答えは正しいです

于 2012-09-20T08:44:08.350 に答える
1

まず、 for ループが間違っています。試す:

for(var i = 1; i <= 3; i++) {
   //code
}

次に、ループ内で毎回要素を取得する代わりに、次を使用できますthis

this.style.backgroundColor = document.getElementById('userInput').value;
于 2012-09-20T08:17:22.177 に答える