2012-03-08 8 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/

これは、SPANをクリックして、その後ではない列にものにそれを追加し、すべてのTD要素からカスタムクラスを削除します。ある要素に対して.index()を呼び出すと、兄弟要素に基づいてその要素のインデックスが取得されます。

0

colは可変なので、文字列連結を使用する必要があります。前もって:notを入力する必要があります。ここで

 
var col = $(this).parent().children().index($(this))-1; 
$("#myTable td:not(:nth-child("+col+"))").addClass("myClass"); 
関連する問題