将事件绑定到多重附加数据 [英] Bind events to mutliple appended data

查看:97
本文介绍了将事件绑定到多重附加数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用jQuery将一些数据发布到处理它的PHP脚本,然后附加回显的数据。现在,在数据中还有一些jQuery脚本回应它一切正常,只要您不向脚本发送两个数据实例即可。



< 解释:想象一下,我已经发布了一些文本(比如说A)到处理PHP脚本,然后将数据插入到数据库中并与删除按钮一起回显数据;现在删除按钮可以正常工作(删除和所有..),但是如果我向处理器发送另一段文本(可以说是B)(不需要在发布之间重新加载页面),并且只与删除按钮一起回显数据第一个被删除,但第二个没有。



代码表示



在不重新加载页面的情况下发布两个文本字符串(text1& text2),然后添加div;他们每个人都有删除按钮和文本,但点击事件只附加到第一个删除按钮,无论多少次我点击第二个删除按钮,它什么都不做。

 < div class =a> text1< div class =delete> X< / div>< / div> //这个获得点击事件
< div class =b> text2< div class =delete> X< / div>< / div> //这个不是

下面是使用的脚本(简体)

 < script> 
$(document).ready(function(){
$(。delete)。click(function(){
$(this).hide();
});
});
< / script>

注意:两次,无需重新加载页面;问题在重新加载页面时消失。






要了解更多信息,请发表评论
<由于您动态创建元素,因此您必须使用 .on() <>来使用事件委托。

  $(document).on('click','。delete',function(){
$(this ).hide()
});

另外,如果您替换 document 带一个静态父选择器到 .delete


I am using jQuery to post some data to a PHP script that processes it and then appends the echoed data. Now there is also some jQuery script among the data echoed it all works fine and well, as long as you don't send two instances of data to the script.

Explanation: Imagine that I have posted some text (Let's say A) to the processing PHP script which then inserts the data into the db and echoes the data along with a delete button; now the delete button works fine (it deletes and all..) but if I post another piece of text (Lets say B) to the processor (without reloading the page between postings) and echo out the data along with the delete button, only the first one gets deleted but the second one doesn't.

Code representation

Two text strings are posted (text1 & text2) without reloading the page, then a div gets appended; each of them has the delete button and the text, but the click event is attached only to the first delete button and no matter how many times I click the second delete button it doesn't do anything.

<div class="a">text1<div class="delete">X</div></div> // this one gets the click event 
<div class="b">text2<div class="delete">X</div></div> // this one doesn't

Below is the script used (simplified)

<script>
$(document).ready(function () { 
    $(".delete").click(function () {
         $(this).hide();
    });
});
</script>

Note: the above javascript is echoed out twice since you post some text twice without reloading the page; the problem disappears when reloading the page.


For more clarification please leave a comment

解决方案

Since you're dynamically creating the elements, you have to use event delegation using .on()

$(document).on('click','.delete',function() {
    $(this).hide()
});

Also, it is better for performance if you replace document with a static parent selector to .delete

这篇关于将事件绑定到多重附加数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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