I have multiple classes on a page of the same name. I then have a .click() event in my JS. What I want to happen is the click event only happen once, regardless of multiple classes on my page.

The scenario is that I am using AJAX to add to cart. Sometimes on the home page there might be a featured product and a top offer which means that the same class .add .#productid# is there and when clicked the add to cart AJAX is fired twice.

我想制作"点击区域",这样我就可以了.容器名称.加上#pid#因此提供独特的点击.

这是唯一的解决办法吗?

<div class="addproduct 151">product info</div>
<div class="addproduct 151">product info</div>
<div class="addproduct 151">product info</div>
<div class="addproduct 151">product info</div>
<div class="addproduct 151">product info</div>


$(".addproduct").click(function(){//do something fired 5 times});

推荐答案

抱歉撞了这根旧线.我现在也有同样的问题,我想分享我的解决方案.

$(".yourButtonClass").on('click', function(event){
    event.stopPropagation();
    event.stopImmediatePropagation();
    //(... rest of your JS code)
});

event.StopPropagation and event.StopImmediatePropagation() should do the trick.

有一个.事件处理程序的类 Select 器将产生bubbling个click事件(有时指向父元素,有时指向DOM中的子元素).

event.StopPropagation()方法确保事件不会冒泡到父元素,而event.StopImmediatePropagation()方法确保事件不会冒泡到所需类 Select 器的子元素.

资料来源: https://api.jquery.com/event.stoppropagation/https://api.jquery.com/event.stopimmediatepropagation/

Jquery相关问答推荐

bootstrap - Select Select 器不能在下拉菜单中 Select

无法使用 HTML 设置未定义的 jQuery UI 自动完成的属性_renderItem

未捕获的类型错误:无法读取未定义的属性toLowerCase

提交前添加 POST 参数

如何访问 JSON 对象名称/值?

如何在 Slick 轮播项目之间添加空格

找到下一个匹配的sibling 姐妹的有效,简洁的方法?

Rails,单击link_to helper后未加载javascript

删除所有子元素的 CLASS

调整浏览器大小时调整jqGrid的大小?

JQuery html() 与 innerHTML

为什么 Chrome 会忽略本地 jQuery cookie?

使用 jQuery 获取选定的选项 id

带有 jquery.animate() 的 CSS 旋转跨浏览器

停止输入/书写后如何触发输入文本中的事件?

带有 jquery 的 jsonp

获取没有在css中设置高度的div的高度

jQuery: Select 不为空的数据属性?

在某个点停止固定位置滚动?

HTMLCollection、NodeLists 和对象数组之间的区别