我是网络开发的新手。我目前正在使用 tablesorter jquery 插件创建一个动态表,用户可以在其中添加和删除行。我无法在单击时更改新 创建的行的背景颜色。它适用于在 html 中硬编码的行。相关代码如下:
$(document).ready(
function() {
$('table.tablesorter td').click(
function (event) {
$(this).parent('tr').toggleClass('rowclick');
$(this).parent('tr').siblings().removeClass('rowclick');
});
}
)
rowclick 在这里是一个 CSS 类:
table.tablesorter tbody tr.rowclick td {
background-color: #8dbdd8;
}
我已尝试将以下内容添加到添加新行的 Javascript 函数中:
var createClickHandler =
function(newrow) {
return function(event) {
//alert(newrow.cells[0].childNodes[0].data);
newrow.toggleClass('rowclick');
newrow.siblings().removeClass('rowclick');
};
}
row.onclick = createClickHandler(row);
当我单击新行时,警报会在该行的第一列中正确显示文本。但是,我的新行不响应 CSS 类。有人有主意吗?
我还应该提到,在应用 clickHandler 之前我已经更新了 tablesorter:
$("#TASKTABLE").trigger("update");
$("#TASKTABLE").trigger("appendCache");
最佳答案
委托(delegate)可点击的 td
元素,例如:
$('table.tablesorter').on('click','td', function(){
使用 jQuery 1.7 中的 .on()
:
As of jQuery 1.7, the .on() method provides all functionality required for attaching event >handlers. For help in converting from older jQuery event methods, see .bind(), .delegate(), >and .live(). To remove events bound with .on(), see .off(). To attach an event that runs >only once and then removes itself, see .one()
关于带有新创建行的 Javascript tr click 事件(更新 css),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11252996/