我正在向表中动态添加行。每一行都是父行或子行。我希望在单击其父行时切换子行的可见性。
if (response != null && response != "")
{
$(response).each(
function()
{
if (this.name == "Opening Balance") // opening balance
{
$('#receipt_table').append(
'<tr class="accordion-toggle" data-toggle="collapse"><th><b>' + this.name
+ '</b></td><th></th><th style="text-align:right"><b>' + this.amount
+ '</b></th></tr>');
receipt_total = this.amount;
}
else if (this.flagGSL == "O" && this.flagPC=="P")
{
$('#receipt_table').append(
'<tr id="'+this.name+'" class="header" bgcolor = #ffff10><td> ' + this.name + '</td><td style="text-align:right">'
+ this.amount + '</td><td></td></tr>');
var myEl = document.getElementById(this.name);
myEl.addEventListener('click', function() {
alert('Clicked');
}, false);
}
else if (this.flagGSL == "O" && this.flagPC=="C")
{
$('#receipt_table').append(
'<tr class="child"><td> ' + this.name + '</td><td style="text-align:right">'
+ this.amount + '</td><td></td></tr>');
}
});
}
在上面的代码中,父行的名称与其名称相同。它的孩子将上课为“孩子”。请建议我使用它来切换子行的解决方案。
答案 0 :(得分:1)
您需要分离动态内容和事件处理程序
if (response != null && response != "") {
$(response).each(function () {
if (this.name == "Opening Balance") // opening balance
{
$('#receipt_table').append(
'<tr class="accordion-toggle" data-toggle="collapse"><th><b>' + this.name + '</b></td><th></th><th style="text-align:right"><b>' + this.amount + '</b></th></tr>');
receipt_total = this.amount;
} else if (this.flagGSL == "O" && this.flagPC == "P") {
$('#receipt_table').append(
'<tr id="' + this.name + '" class="header" bgcolor = #ffff10><td> ' + this.name + '</td><td style="text-align:right">' + this.amount + '</td><td></td></tr>');
} else if (this.flagGSL == "O" && this.flagPC == "C") {
$('#receipt_table').append(
'<tr class="child"><td> ' + this.name + '</td><td style="text-align:right">' + this.amount + '</td><td></td></tr>');
}
});
}
然后在dom ready handler
上jQuery(function () {
$('#receipt_table').on('click', '.header', function () {
$(this).nextUntil('.header', '.child').toggle()
})
})