2

JavaScript を使用してテーブルの行の背景を変更しようとしましたが、うまくいきません。これは私のコードです。ただし、htmlとその作業でテーブルを作成しようとしました。PS : webkit を使用したいです。

コード :

var table = document.getElementById("tab");
var rowCount = table.rows.length;


for(var i=0;i<6;i++) {     
   row = table.insertRow(rowCount);
   row.id = "row"+i;
   cell1 = row.insertCell(0);
   var content = document.createElement("output");                
   content.innerHTML = i ;
   cell1.appendChild(content);
   rowCount++;
}


 $(document).ready(function(){
        $('td').each(function(i) {     
             $('#tab').on('click', '#row'+i, function(){
                document.getElementById("row"+i).style.background = 'white';
                 //alert(i);
             });   
        });   

     //example2
     $('#td1').on('click', function(){
                document.getElementById("td1").style.background = 'white';
             });   
 }); 
4

5 に答える 5

2

あなたが直面している問題は、 で背景のグラデーションをTD設定してから、 の背景色を設定しているためですTR。TD は TR 内にあるため、変更が適用されていないだけです。

于 2012-12-19T17:02:13.827 に答える
2

特に次の必要がない場合は、ループ内でイベント ハンドラーを割り当てないでください。

$('#tab').on('click', 'tr', function () {
    $('td,th', this).css('background', 'white');
});         

フィドル

于 2012-12-19T17:06:50.083 に答える
1

これは backgroundColor であり、background ではありません。

于 2012-12-19T16:58:59.867 に答える
1

最初の問題は閉鎖の問題です.. ..

Click イベントは常にiの最後のインスタンスを指します。

コードをこれに変更します

$('td').each(function(i) {
     (function(num) {
        $('#tab').on('click', '#row' + num, function() {
           document.getElementById("row" + num).style.background = '';
          //alert(i);
        });
     })(i)
 });

これは、機能しないコードの主な理由ではないかもしれません..

于 2012-12-19T17:06:09.727 に答える
0

行全体または現在のセルの色を変更しますか? 現在のセレクターは特定のセルにのみ適用されます。

// for the complete row
$(document).ready(function(){
    $('td').on('click',function(){
        $(this).closest('tr').find('td').css({'background':'red'});
    });
}); 

// or for the active cell..
$(document).ready(function(){
    $('td').on('click',function(){
        $(this).css({'background':'red'});
    });
}); 

行ソリューションについては、このフィドルhttp://jsfiddle.net/axelmichel/2KUCz/を参照してください。テーブルごとに異なる動作が必要な場合は、セレクターを次のように変更できます。

$('#tab').find.('td').on('click',...
于 2012-12-19T17:10:41.560 に答える