2012-03-08 38 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"); 
相關問題