添加点击功能来动态创建html标签 [英] Add click function to dynamically created html tags

查看:136
本文介绍了添加点击功能来动态创建html标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个包含多个其他div的div。其他每个div都有一个叫record的类。

 < div id =resultContainer>我只使用这个类来选择所有这些div。 
< div class =record> result1< / div>
< div class =record> result2< / div>
< div class =record> result3< / div>
< div class =record> result4< / div>
< / div>

我还添加了一个点击事件=



<$点击(功能(e){
在这里做的东西....
});

现在我要动态添加另一个div。

  $(#resultContainer)。append(< div class ='record'> result5> / div>); 

但是现在这个点击事件并没有被添加到记录中。



我的想法是创建一个名为 update()的函数来执行 $(。record .... code并在每次添加记录时调用该函数,但原始div不止一次执行此操作!



如何获取所有我的div不管何时被添加,在之前做点东西...... 恰好点击一次?



< p $>
$ b

另外,我也在动态div上有按钮,所以一个解决方案能够处理这样的事情: $ (.save)。button({icons:{primary:'ui-icon-disk'},text:false}); 会更好。


<在这种情况下,不要使用 .live()。这是 jQuery的 .delegate()方法,这更有效('。record','click',function(){$($))。

  $(#resultContainer b $ b //在这里做东西... 
});

只需在 resultContainer 内单击即可处理以查看它们是否匹配 .record ,其中 .live()需要处理页面上的每次点击。

So I have a div that contains a number of other divs. Each of these other divs has a class called record. I only use this class to select all of these divs.

<div id = "resultContainer">
   <div class="record">result1</div>
   <div class="record">result2</div>
   <div class="record">result3</div>
   <div class="record">result4</div>
</div>

I also add a click event=

$(".record").click(function(e) {
        do stuff here....
    });

Now I want to dynamically add another div.

$("#resultContainer").append("<div class='record'>result5>/div>");

But now that click event is not added to the record.

My idea was to create a function called update() that executed the $(".record.... code and call the function each time I added a record. But then the original divs do the action more than once!

How do I get all of my divs, regardless of when they were added, to before the do stuff here... exactly once when clicked?

thanks!

In addition, I also have buttons on the dynamic div. So a solution that was able to handle something lik this: $(".save").button({ icons: { primary: 'ui-icon-disk' }, text: false }); would be preferable.

解决方案

Don't use .live() in this case. This is a perfect situation for jQuery's .delegate() method, which is more efficient.

$("#resultContainer").delegate('.record','click',function() {
    // do stuff here...
});

Only clicks inside the resultContainer need to be processed to see if they match .record, where .live() will need to process every click on the page.

这篇关于添加点击功能来动态创建html标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆