繁体   English   中英

使用JavaScript更改行表颜色

[英]Change row table color with JavaScript

我尝试使用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';
             });   
 }); 

您遇到的问题是因为要在TD上设置背景渐变,然后再设置TR的背景颜色。 由于TD在TR内,因此您只是看不到您所做的更改。

您不应该在循环中分配事件处理程序,尤其是在您不需要:

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

摆弄

它是backgroundColor,不是background。

第一个问题是关闭问题

Click事件将始终指向i最后一个实例。

将您的代码更改为此

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

这可能不是非功能代码的主要原因。

您要更改整行或当前单元格的颜色吗? 您当前的选择器仅适用于特定的单元格。

// 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',...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM