How to solve the problem: add event for dynamic elements

Today, I tried to solve a problem: When I click the header of a table, then the table will add a new row, and if I click the added row, the row will alert its row number.
This is very easy problem, but I just express the idea about how to solve a problem that is similar, and the progress.
First step, I finish the addition of a new row functions easily, see the code below:

$(document).ready(function(){
$("#tb1 tr").click(function(){
$("#tb1").append("<tr><td>you click me</td></tr>");
})

$("#tb1 td").each(function(i){
$(this).click(function(){
alert(i);
});
});
});

But the click event does not work. And the reason is clear: when the page finish loading, there is any TB element in the table. So I consider I should add the click event when I create the new row! See the changed code below:

$(document).ready(function(){
$("#tb1 tr").eq(0).click(function(){
$("#tb1").append("<tr><td>you click me</td></tr>");
$("#tb1 td").each(function(i){
$(this).click(function(){
alert($(this).parent().index());
});
});
});
});

Now the click event will be triggered, but when I click the first added row, the same message will be shown several times! So I realized that I made a mistake: when I created a new row, I added a click event for every TB element every time. So I change the script:

$(document).ready(function(){
$("#tb1 tr").eq(0).click(function(){
$("#tb1").append("<tr><td>you click me</td></tr>");
$("#tb1 td").filter(":last").click(function(){
alert($(this).parent().index());
});
})
});


OK, the script works correctly now!
[b]At last, I make a summary about how to solve this kind problem:
1 add new element normally;
2 add the trigger event when you create the new element;
3 just add the trigger event for the element what you created just now.[/b]
This is my idea to solve this kind of problem, if you have a better idea, please share it with us. Thank you very much.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值