Jquery点击事件触发两次

Jquery click event fire twice

本文关键字:两次 事件 Jquery      更新时间:2023-09-26

我正在用Jquery构建一些东西,并且我正在进行一些Ajax调用。因此,在ajax调用之后,我需要调用函数来再次跟踪对某些元素的单击。下面是这样一个函数的例子:

$(document).ready(function () {
    initSomething();
});
function initSomething(){
    $('.something').click(function(){
        alert('hello');
    });
}

现在是ajax函数:

$('#AddSomething').click(function(){
    $.post('somewhere.php',{data},function(data){
        initSomething();
    });
});

问题是:我觉得当我initSomething();第二次,它就像是在读取一个click事件,这个事件已经被第一个initSomething在document ready上调用。

所以我尝试了e.p preventdefault和e.p preventpropagation()之类的东西,但它似乎不起作用,我错过了什么?

谢谢你的回答,祝你有美好的一天!

编辑:正如在答案中看到的,我忘记说Ajax调用是在DOM中插入新的。something元素…

编辑2:这里有一个jsfiddle: https://jsfiddle.net/wpsnz7op/

尝试.off() api删除已经附加的事件,并像下面这样重新分配事件。

function initSomething(){
    $('.something').off('click').click(function(){
        alert('hello');
    });
}

希望对您有所帮助....

不需要从我看到的代码中重新绑定点击。

只要不重新绑定,你就不会有多次点击的问题。

使用事件委托代替。

 $(document).on('click','.something',function(){
        alert('hello');
    });

那么在ajax之后就不需要调用initSomething();函数了