论坛首页 Web前端技术论坛

How to solve the problem: add event for dynamic elements

浏览 1900 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2011-07-29  
   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.
   发表时间:2011-08-01  
live()
0 请登录后投票
   发表时间:2011-08-03  
bitsmix 写道
live()

我用live试了好像没有起作用,你自己在chrome上面测试一下吧。本来这个是一个很简单的问题,我之所以写的那么长,是想把我的思考过程展现出来,遇见了同类似的问题不用在浪费时间。
0 请登录后投票
论坛首页 Web前端技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics