2012-03-08 40 views
0

我需要能够将样式应用于表中的所有单元,但当前列中的单元除外。将样式应用于表除当前列中的单元外

我想要做这样的事情,但它似乎并没有工作。我错过了什么?

var col = $(this).parent().children().index($(this)); 
    $("#myTable td:nth-child(:not(col-1))").addClass("myClass"); 

    <table id="myTable"> 
    <tr> 
     <td>col 1</td> 
     <td>col 2</td> 
    </tr> 
    <tr> 
     <td><span class="click">click</span></td> 
     <td><span class="click">click</span></td> 
    </tr> 
    </table> 

回答

1
//bind click event handler to the `.click` elements 
$('#myTable').find('.click').on('click', function() { 

    //remove class from all TDs 
    $('#myTable').find('td').removeClass('myClass'); 

    //get the index of the clicked element based on its parents siblings 
    var index = $(this).closest('td').index(); 

    //iterate though each TD element in the table and add the class to it if it isn't the same index as the clicked element 
    $.each($('#myTable').find('tr').children(), function() { 
     if ($(this).index() != index) { 
      $(this).addClass('myClass'); 
     } 
    }); 
}); 

这里是一个演示:http://jsfiddle.net/hU5qW/1/

这将删除所有的TD元素自定义类,然后将其添加到那些不列与SPAN点击。请注意,如果您在某个元素上调用.index(),则将根据其元素的同级元素获取该元素的索引。

0

由于col是一个变量,你必须使用字符串连接。您之前还需要放置:not

 
var col = $(this).parent().children().index($(this))-1; 
$("#myTable td:not(:nth-child("+col+"))").addClass("myClass"); 
相关问题