javascript - 点击事件重复4次

标签 javascript jquery

我的代码

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/

相关文章:

javascript - 改变获取期权值(value)

javascript - 经度纬度 (WGS84) 到多圆锥变换转换

javascript - 在 JavaScript 多维对象中引用数字

javascript - 如何找到容器内的所有事件并委托(delegate)它们

javascript - 如何将 json 对象设置为隐藏输入

javascript - Node JS 重定向给了我一堆 html 文本

javascript - 可以在Javascript中使用reduce编写bigram(或ngram)函数吗?

CSS 使用类或 javascript 更改样式/动画样式?

javascript - 如何过滤JSON数据中的价格范围: Javascript or jQuery

javascript - 滚动时在视口(viewport)上正确对齐 div