2015-07-21 48 views
4

我有兩個表:使用jQuery突顯TR的還是TD的

<table class="highlight_row" id="table1"> 
    <tr id="first_row"> 
    <td><input type="checkbox" id="first">first thing</td> 
    <td><input type="checkbox" id="second">second thing</td>  
    <td><input type="checkbox" id="third">third thing</td> 
    </tr> 
</table> 

<table class="highlight_td" id="table2"> 
    <tr id="second_row"> 
    <td><input type="checkbox" id="fourth">fourth thing</td> 
    <td><input type="checkbox" id="fifth">fifth thing</td>  
    <td><input type="checkbox" id="sixth">sixth thing</td>  
    </tr> 
</table> 

,我試圖者區分他們 - 當我在第一個表檢查所有箱子,我想這全行突出,當我在第二張表格中選中一個框時,我只需要突出顯示td。我可以得到突出顯示的行(使用addClass()爲'selected'顏色),但是當我指定表類時,我仍然得到第二個表的整行,當我只想要td(由於我增加了更多的表格,因此從長遠來看,我可以通過班級而不是id來識別)。

jQuery代碼:

$(".highlight_row").click(function(){ 
    $(":checkbox").change(function() { 
    $(this).closest("tr").toggleClass("selected", this.checked) 
    }) 
}); 
+0

安置自己的jQuery的親本細胞類 - I F鰻魚就像你可能會選擇所有'td'元素作爲你的第一個例子。 – Purag

+0

你不能在一個頁面中重複ID ...他們根據定義是唯一的。郵編不工作,所以人們可以幫助你找出原因。您通過更多的方式學習,我們不必重新發明 – charlietfl

+0

我們可以看到您的jQuery事件調用嗎?正如上面的用戶所說,可能會抓住錯誤的元素 – code

回答

-2

對於行使用:

.highlight_row .selected { 
    background: yellow; 
} 

的電池使用:

.highlight_td .selected td:nth-child(1) { 
    background: yellow; 
} 
1

喜歡的東西this fiddle,也許?

您的HTML。

CSS:

.highlight { background: #ff0; } 

JS:

$("#table1 input[type=checkbox]").on('click', function() 
{ 
    $(this).parent().parent().toggleClass('highlight'); 
}); 

$("#table2 input[type=checkbox]").on('click', function() 
{ 
    $(this).parent().toggleClass('highlight'); 
}); 
0

對於第一個表,你會想EVAL所有複選框,這樣它不會取消高亮顯示。第二個表更容易。

小提琴:所示添加在整個表點擊處理程序中的更改處理http://jsfiddle.net/24vm61dk/

$(function() { 
    // Highlight Row 
    $('#table1 input[type="checkbox"]').on('change', function() { 
     var anyChecked = false; 
     $(this).closest('tr').find('input[type="checkbox"]').each(function() { 
      if ($(this).prop('checked')) { 
       anyChecked = true; 
      } 
     }); 
     if (anyChecked) { 
      $(this).closest('tr').addClass('highlight'); 
     } else { 
      $(this).closest('tr').removeClass('highlight'); 
     } 
    }); 

    // Highlight Cell 
    $('#table2 input[type="checkbox"]').on('change', function() { 
     var checked = $(this).prop('checked'); 
     if (checked) { 
      $(this).closest('td').addClass('highlight'); 
     } else { 
      $(this).closest('td').removeClass('highlight'); 
     } 
    }); 
}); 
0

代碼。

這會導致複合事件,並且如果用戶在表中點擊很多,則會導致嚴重的瀏覽器性能問題。

簡而言之,點擊表4次,每一個複選框被改變時,就會引發四化處理

一個簡單的方法爲行高亮是使用選中的複選框的計數行中確定類狀態

$('table.highlight_row input:checkbox').change(function(){ 
     var $row = $(this).closest('tr'), 
      hasChecked = $row.find(':checkbox:checked').length; 

     $row.toggleClass('selected', hasChecked);   
}); 

細胞高亮更容易...只需撥動基於選中狀態

$('table.highlight_td input:checkbox').change(function(){ 
    $(this).parent().toggleClass('selected', this.checked); 
});