[英]Javascript to Highlight Table Row Only When inside 'a' tag is clicked
我目前有一個html表(具有2列),我正在嘗試向該表添加各種效果,例如表行懸停效果,表單擊效果等...這是我現在正在使用的腳本,因此可以正常工作遠:
<head>
<script type="text/javascript">
$(document).ready(function(){
//the following script is to change the table row bg color when clicked
$('tr').click(function(){
$('tr td').css({ 'background' : 'none'});
$('td', this).css({ 'background-color' : '#CCC' });
});
//the following script is for the table row hover effect
$('tr').hover(function() {
$(this).css('background-color', '#FFFF99');
},
function() {
$(this).css('background-color', '#FFFFFF');
$(this).contents('td').css('border', 'none');
});
});
</script>
</head>
<body>
<table>
<tr>
<td> <a href="#">Movie Part 1</a></td>
<td>01:23:26</td>
</tr>
<tr>
<td> <a href="#">Movie Part 1</a></td>
<td>01:23:26</td>
</tr>
</table>
</body>
從上面的模板中,您可以看到我有2列用於此表,其中1列具有帶有href鏈接的標簽,而另一列則沒有任何標簽。
就像我上面提到的那樣,單擊時我用來突出顯示表格行的腳本起作用。 但是我試圖稍微修改一下腳本,以便僅在單擊“ tr td”內的“ a”標簽時才執行單擊效果。 現在,突出顯示的表格行與在“ tr”區域內單擊的位置無關。 即使單擊“ tr”內沒有鏈接的第二列,它也會突出顯示。
如何修改上面的腳本,以便僅在單擊表行第一列中的“ a”標簽時才突出顯示整個表行?
$('tr').on('click','a', function () {
$(this).closest('tr').css({ 'background-color' : '#ccc'});
});
我認為您只需要更改TR
的背景顏色,而不必更改TD
的背景顏色。 如果我弄錯了,請改用此方法:
$('tr').on('click','a', function () {
$(this).closest('tr').children('td').css({ 'background-color' : '#ccc'});
});
$('tr').delegate('a', 'click', function () {
$(this).closest('tr').children('td').css({ 'background-color' : '#ccc' });
});
根據下面的評論,您希望在單擊另一行時將其還原為正常的背景色。
為了有效地做到這一點,建議您使用CSS規則。 哎呀,想一想,即使是先回答問題,我們也應該這樣做。
首先,如下定義CSS規則:
tr { background-color:#fff; /* or your default */ }
tr.selected { background-color:#ddd; /* or your selected color */ }
然后使用jQuery進行切換:
$('tr').delegate('a', 'click', function () {
$(this)
.closest('tr').addClass('selected')
.siblings('tr').removeClass('selected')
;
});
如果僅修改tr
對您不起作用,請按如下所示修改CSS規則:
tr td { background-color:#fff; /* or your default */ }
tr.selected td { background-color:#ddd; /* or your selected color */ }
您可以使用它檢查帶有href的'tr'是否低於'tr'
$('tr').click(function(e) {
if (e.target.href){
$('tr td').css({
'background': 'none'
});
$('td', this).css({
'background-color': '#CCC'
});
}
});
PS。 感謝Richard Neil Ilagan意識到由於事件冒泡而使用if(e.target.href.length> 0)引發的異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.