簡體   English   中英

使用jQuery不會更改tr的背景色

[英]Background color of tr is not changing using jquery

我想在單擊tr的子級td時更改其背景色。我無法在on上添加onclick ,因為它是在渲染后從asp.net的gridview控件動態生成的。

我的標記是

<tbody>
  <tr>
    <td style="width:27%;"><span onclick="SelectAddressRow(this)">Ajish</span></td>
    <td style="width:40%;"><span onclick="SelectAddressRow(this)">22</span></td>
    <td style="width:33%;"><span onclick="SelectAddressRow(this)">Male</span></td>
 </tr>
</tbody>

我的代碼是

function SelectAddressRow(column) {
  var tableRow=$(column).parent();
  $(tableRow).parent().css({ "background-color": "#B3B3B3" });
}

但它不起作用,但是如果將語句替換為td,則會影響td

$(tableRow).css({ "background-color": "#B3B3B3" });

那這種方法呢? 由於您使用的是jQuery,因此使用內聯javascript沒有任何意義:

$('table').on('click', 'span', function() {
    $(this).closest('tr').addClass('selected');
});

CSS:

.selected {
    background: #B3B3B3;
}

http://jsfiddle.net/m5D85/

你很親密 您已將參數定義為column並使用Column

function SelectAddressRow(column) {
  var tableRow=$(column).parent();
  $(tableRow).parent().css({ "background-color": "#B3B3B3" });
}

演示

或者,您可以使用.closest()

function SelectAddressRow(column) {
  $(column).closest('tr').css({ "background-color": "#B3B3B3" });
}

演示

試試這個:

<tbody>
  <tr>
    <td style="width:27%;"><span onclick="SelectAddressRow($(this).closest('tr'))">Ajish</span></td>
    <td style="width:40%;"><span onclick="SelectAddressRow($(this).closest('tr'))">22</span></td>
    <td style="width:33%;"><span onclick="SelectAddressRow($(this).closest('tr'))">Male</span></td>
 </tr>
</tbody>

並將函數更改為如下所示:

function SelectAddressRow(row) {
  var tableRow=row;
  tableRow.css({ "background-color": "#B3B3B3" });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM