浏览 1900 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2011-07-29
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. 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |
发表时间:2011-08-01
live()
|
|
返回顶楼 | |
发表时间:2011-08-03
bitsmix 写道 live()
我用live试了好像没有起作用,你自己在chrome上面测试一下吧。本来这个是一个很简单的问题,我之所以写的那么长,是想把我的思考过程展现出来,遇见了同类似的问题不用在浪费时间。 |
|
返回顶楼 | |