jQuery $(“。class”)。click(); -多个元素,单击事件一次


80

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

场景是我正在使用AJAX添加到购物车。有时,主页上可能会有特色产品和最高报价,这意味着存在同一类.add。#productid#,并且在单击添加到购物车AJAX时会触发两次。

我考虑过要制作“点击区域”,所以我会有.container-name .add。#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});

请发布您的代码,您的发言对我而言没有任何意义。
拉撒路

是的,请发布您的JavaScript代码。
Yngve B-Nilsen

1
它应该只触发一次,或者是HTML的问题-可能是一个addproduct类嵌套在另一个类中,或者是处理程序中的错误,一次单击就触发了ajax两次,无论是哪种方式,我们都需要,因此请参见完整代码确定。
西蒙

3
可怕的提问和回答。我遇到了类似的问题,但最初的发帖人在哪里都没有提到解决问题的方法或方法...令人沮丧的是,人们无法正确使用此网站,但希望成为任何级别的开发人员。
ocergynohtna 2012年

使用data-id =“ 151”,然后使用$(this).data('id')
Andres SK

Answers:


114

很抱歉撞到这个旧线程。我现在遇到相同的问题,我想分享自己的解决方案。

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

event.StopPropagation并且event.StopImmediatePropagation()应该做到这一点。

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

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

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


1
这是正确的解决方案。如果您使用jQuery调用类,则它会冒泡到其他元素并注册多次单击。如何解决该单击事件到其他元素的传播。我认为其他一些答案误解了这里最有可能发生的事情。
RATKNUKKL

86
$(document).on('click', '.addproduct', function () {
    // your function here
});

它有效吗?从未见过像这样使用函数
Nabeel Khan

我应该如何从另一个事件中调用给出的答案?
Murad Hasan

1
尝试了一切,这是唯一有效的解决方案。
马特

第二个参数的解释:A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element.
zwlxt

45

我们可以看到您的点击处理程序吗?您要将5个侦听器附加到5个不同的元素。但是,当用户单击元素时,只会触发一个事件。

$(".addproduct").click(function(){
  // Holds the product ID of the clicked element
  var productId = $(this).attr('class').replace('addproduct ', '');

  addToCart(productId);
});

如果此解决方案不起作用,我想看看您的点击处理程序。


29

当您单击带有addproduct类的div时,将为该特定元素而不是五个触发一个事件。如果事件被触发5次,则您的代码有误。


23
我喜欢这个答案说明显而易见的内容,然后查询者说他们将检查他们的代码,好像这不是他们最初要做的事情:D。
KI4JGT

1
我很惊讶这是被接受的答案。正如伊万·卡拉法蒂奇(IvanKalafatić)提到的那样,问题在于点击事件正在传播到其他元素。解决的办法是停止这种传播。请参阅IvanKalafatić的答案以了解如何执行此操作。编辑:只是注意到正确的答案实际上是伊万·卡拉法蒂奇(IvanKalafatić)而不是Machavity(编辑的)。解决了我的错误。
RATKNUKKL

14

在这种情况下,我会尝试:

$(document).on('click','.addproduct', function(){

    //your code here

 });

然后,如果您需要在具有相同类的其他元素上单击以执行某些操作,则可以遍历这些元素:

$(document).on('click','.addproduct', function(){
   $('.addproduct').each( function(){

      //your code here
     }
  );
 }
);

11

我想您将点击事件添加了五次。尝试计算您执行此操作的次数。

console.log('add click event')
$(".addproduct").click(function(){ });

使用AngularJS,我注意到它已复制脚本标签以测试x倍的时间!感谢您提供可能的解决方案。
Dean Meehan 2015年

8

这应该可以解决,并且应该是一个好习惯:.unbind()

$(".addproduct").unbind().click(function(){
   //do something 
});

请注意,unbind已被弃用(来自api.jquery.com/unbind):从jQuery 3.0开始,.unbind()已被弃用。自jQuery 1.7起,它已由.off()方法取代,因此不鼓励使用它。
Tomer

6

我通过使用内联jquery函数调用解决了它

<input type="text" name="testfield" onClick="return testFunction(this)" /> 

<script>
  function testFunction(current){
     // your code go here
  }
</script>

9
那不是jQuery。

你救了我的一天,老兄!
的Smaine

5

我只是有同样的问题。在我的情况下,PHP代码生成相同的jQuery代码的次数很少,这就是多次触发。

<a href="#popraw" class="report" rel="884(PHP MULTIPLE GENERATER NUMBERS)">Popraw / Zgłoś</a>

(PHP MULTIGEN GENERATER NUMBERS也多次生成相同的代码)

<script type="text/javascript">
$('.report').click(function(){...});
</script>

我的解决方案是将脚本分离到另一个php文件中,并一次加载该文件。


您的评论使我想到了解决方案-我遇到了同样的问题,一键触发了每个元素的事件。这是因为我将脚本卡在了多次加载的局部视图(asp mvc)中。谢谢。
韩山

2

只需在此处输入代码,在JQuery中,将触发一个事件,您只需检查文件中类的出现次数,并为下一个逻辑使用循环即可。通过JQuery标识任何类,标签或任何DOM元素的出现次数:var len = $(“。addproduct”)。length;

 $(".addproduct").click(function(){
       var len = $(".addproduct").length; 
       for(var i=0;i<len;i++){
          ...
        }
 });

1

我有同样的问题。原因是我多次使用相同的jquery。他陷入了困境。

$ (". AddProduct"). click (function () {});
$ (". AddProduct"). click (function () {});
$ (". AddProduct"). click (function () {});
$ (". AddProduct"). click (function () {});
$ (". AddProduct"). click (function () {});

为此原因多次射击


1

我在项目中亲自尝试过。

我在表中的所有行都有一个“联系人”类:

我在表中的所有行都有一个“联系人”类。

我的代码如下所示:

var contactManager = {};

contactManager.showEditTools = function(row) {
  console.debug(row);
}

$('.contact').click(function(event){
  console.log("this should appear just once!");
  alert("I hope this will appear just once!");
  contactManager.showEditTools(event);
});

当执行代码时,我首先害怕在Firebug控制台中看到整个行:

执行代码后的Firebug控制台屏幕截图

但是后来我意识到没有触发click事件,因为没有出现警报对话框。Firebug仅向您显示受点击覆盖影响的元素。因此,无需担心。


1

尝试使用.off()处理程序:

$(function () {
    $(".archive-link").click(function (e) {
        var linkObj = $(this);
        var cb = $("#confirm-modal");
        cb.find(".modal-body").append("<p>Warning message.</p>");
        cb.modal('show'); 
        cb.find(".confirm-yes").click(function () {
            $(this).off(); //detach this event
            //ajax call yada yada..
        }

我将OK事件模式按钮上的click事件处理程序附加到click具有class的对象的事件上.archive-link

第一次单击时,事件仅在.archive-link我要求函数对(var linkObj)起作用的对象上触发。但是,当我第二次单击相同的链接并在模式上单击“确定”时,该事件将在.archive-link我之前单击的每个对象上触发。

我使用了上面的解决方案,但不幸的是没有用。当我在模式OK按钮单击函数中调用.off()时,传播停止了。我希望这有帮助。


1

这个问题已经解决,也得到了很多答复,但是我想在此添加一些内容。我试图弄清楚为什么我的点击元素会触发77次而不是一次。

在我的代码中,我有一个,运行一个json响应并将其显示为带有按钮的div。然后,我在每个声明了click事件。

$(data).each(function(){
    button = $('<button>');
    button.addClass('test-button');
    button.appendTo("body");

    $('.test-button').click(function(){
        console.log('i was clicked');
    })
})

如果您这样编写代码,则.test-button类将获得多个click事件。例如,我的数据有77行,因此每行将运行77次,这意味着我将拒绝类的click事件77次。当您单击该元素时,它将被触发77次。

但是,如果您这样写:

$(data).each(function(){
    button = $('<button>');
    button.addClass('test-button');
    button.appendTo("body");
})

    $('.test-button').click(function(){
        console.log('i was clicked');
    })

您要在每个元素之后声明click元素。这意味着,每个将运行77次,而click元素将仅被声明一次。因此,如果您单击该元素,它将仅被触发一次。


1

只需在下面的代码中做就可以了

$(".addproduct").on('click', function(event){
    event.stopPropagation();
    event.stopImmediatePropagation();
    getRecord();
});


function getRecord(){
   $(".addproduct").each(function () {
       console.log("test");
       });

}

0

您好,抱歉这篇文章碰到这个问题,我想展示一下我的情况。

我的代码如下所示。

<button onClick="product.delete('1')" class="btn btn-danger">Delete</button>
<button onClick="product.delete('2')" class="btn btn-danger">Delete</button>
<button onClick="product.delete('3')" class="btn btn-danger">Delete</button>
<button onClick="product.delete('4')" class="btn btn-danger">Delete</button>

JavaScript代码

<script>
 var product = {
     //  Define your function
     'add':(product_id)=>{
          //  Do some thing here
     },

     'delete':(product_id)=>{
         //  Do some thig here
     }
 }
</script>

0

$(document).ready(function(){

    $(".addproduct").each(function(){
          $(this).unbind().click(function(){
               console.log('div is clicked, my content => ' + $(this).html());
           });
     });
}); 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="addproduct 151">product info 1</div>
<div class="addproduct 151">product info 2</div>
<div class="addproduct 151">product info 3</div>
<div class="addproduct 151">product info 4</div>
<div class="addproduct 151">product info 5</div>


-5

您的事件仅触发一次...因此此代码可能会起作用

    $(".addproduct,.addproduct,.addproduct,.addproduct,.addproduct").click(function(){//do     something fired 5 times});
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.