我的代码
var post = {};
post.DivPostContent = $('.content');
post.DivPostContent.live({
mouseenter:
function()
{
var post_id = $(this).attr('data-post_id');
var content_id = $('#content' + '_' + post_id);
var link = $('#link' + '_' + post_id);
content_id.find('.post_ratings').hide();
content_id.find('.post_actions').show();
//I removed the click event on a whim, i have no clue why it works
link.unbind('click');
link.click(function(){
post.link_action(post_id);
});
},
mouseleave:
function()
{
//does something
}
});
post.link_action = function(){
//Does some Ajax request
}
在我从“Link”解除点击事件的绑定(bind)之前,它调用了“post.link_action”四次,我试图弄清楚它为什么这样做。经过几个小时一遍又一遍地阅读我的代码后,我心想,让我们尝试删除点击事件,但我错误地将该行放在了错误的位置(我猜是出于沮丧)。我运行了代码,中提琴!有效!如何?我不知道。
现在我的问题是,为什么在添加点击事件之前取消绑定(bind)会阻止该过程重复进行?我真的很想知道为什么。 谢谢。
最佳答案
因为每次你的鼠标进入 post.DivPostContent 对象时,它都会将一个新的点击事件绑定(bind)到你的链接对象;它触发了 4 次,因为您将鼠标悬停了 4 次。
忘记 .live 和 .click;使用 .on 代替并在 mouseenter 事件之外绑定(bind)一次,或者如果您坚持将其绑定(bind)在那里,请在之前使用 .off
$elem.off("click").on("click",function() {});
但是在鼠标中心之外执行一次
关于javascript - 点击事件重复4次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14329906/