`
gteam.yu
  • 浏览: 27780 次
  • 性别: Icon_minigender_1
  • 来自: 成都
最近访客 更多访客>>
社区版块
存档分类
最新评论

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!
   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.

   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.
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics