Jquery点击绑定不工作第二次 [英] Jquery click bind doesn't work second time

查看:128
本文介绍了Jquery点击绑定不工作第二次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个奇怪的行为 a img 标签里面。

i have a strange behaviour with a and with img tag inside.

我有一个包含记录列表的表的php页面。
在每一行的结尾都有一个删除行按钮。

I have a php page with a table that is a list of records. At the end of every row i have a button for delete row.

这是我的表的代码:

<div class='edit' >
    <a id='20' href='#' return;>
        <img src='images/edit.png'  />
    </a>
</div>

每个记录,主表的每一行都有上面的代码,

Every record, every row of the main table, has the code above, with different id each other.

我的脚本代码是:

$("#delete a").click(function(e) {

e.preventDefault();

$('#action').val("delete");
$('#keyAction').val(this.id);

$.ajax({
        type: "POST",
        url: "processAttivita.php",
        data: $("#attivita_form").serialize(),
        error: function(msg) {
            $("#errore").html(msg);
        },
        success: function(msg) {
            // display the errors returned by server side validation (if any)
            ricaricaLista();                

        }
    });     

 // end click delete event  
 });

第一行我试图删除点击图像工作正常。
在第二个,似乎jquery不绑定click事件和默认href的 a 元素发生,保留在同一页上由于# 在href属性。

The first row i try to delete clicking on the image works fine. On the second one it seems that jquery doesn't bind "click" event and default href of a element occurs, remaining on the same page due the "#" in href attribute.

任何想法为什么第二次jquery不拦截点击< a> 元素?

Any ideas why the second time jquery doesn't intercept click on <a> element ?

推荐答案

您使用ID选择器 #delete a 它将只匹配一个(通常是第一个)元素。

You're using an ID selector #delete a which will only match one (generally the first) element.

尝试使用类,例如 .delete a

只有一个元素的原因是因为JQuery优化了以传递到 document.getElementById ,它只返回1个元素。

The reason you only get one element is because JQuery optimizes any selector that begins with # passes through to document.getElementById, which only returns 1 element.

下面是如何使用事件委托来实现相同的事情的示例:

Here's an example of how to use event delegation to achieve the same thing:

$("#tableid").click(".delete a", function(e) {
    // your code
});

你的html需要在你的表上有一个ID,并给出 class = delete到您的删除链接的容器。

Your html would need to have an ID on your table and give class="delete" to the container of your delete links.

这篇关于Jquery点击绑定不工作第二次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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