2012-03-08 5 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"); 
Смежные вопросы