jQuery $(“.class").click(); -多个元素,单击事件一次 [英] jQuery $(".class").click(); - multiple elements, click event once

查看:905
本文介绍了jQuery $(“.class").click(); -多个元素,单击事件一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在同名页面上有多个类.然后,我的JS中有一个.click()事件.我想发生的是,无论页面上有多个类,单击事件都只会发生一次.

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.

这种情况是我正在使用AJAX添加到购物车.有时,在主页上可能会提供特色产品和最优惠的价格,这意味着存在相同的类.add.#productid#,并且在单击添加到购物车AJAX时会触发两次.

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.

我考虑过要制作点击区域",因此我将使用.container-name .add.#pid#,从而带来唯一的点击.

I thought about making 'click areas' so I would have .container-name .add .#pid# therefore giving unique clicks.

这是唯一的解决方案吗?

Is this the only solution?

<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});

推荐答案

为此旧线程加油的道歉.我现在遇到了同样的问题,我想分享自己的解决方案.

Apologies for bumping this old thread. I had the same problem right now, and I wanted to share my solution.

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

event.StopPropagationevent.StopImmediatePropagation()应该可以解决问题.

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

在事件处理程序中使用.class选择器将导致点击事件bubbling(有时是DOM中的Parent元素,有时是子元素).

Having a .class selector for Event handler will result in bubbling of click event (sometimes to Parent element, sometimes to Children elements in DOM).

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

event.StopPropagation() method ensures that event doesn't bubble to Parent elements, while event.StopImmediatePropagation()method ensures that event doesn't bubble to Children elements of desired class selector.

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

这篇关于jQuery $(“.class").click(); -多个元素,单击事件一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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