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

时间:2011-04-06 08:55:07

标签: jquery

我在同名页面上有多个班级。然后我在我的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});

19 个答案:

答案 0 :(得分:61)

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

答案 1 :(得分:54)

抱怨这个老线程。我现在遇到了同样的问题,我想分享我的解决方案。

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

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

使用事件处理程序的.class选择器将导致单击事件bubbling(有时对父元素,有时对DOM中的Children元素)。

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

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

答案 2 :(得分:41)

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

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

  addToCart(productId);
});

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

答案 3 :(得分:28)

当您使用addproduct类单击div时,会针对该特定元素触发一个事件,而不是五个。如果事件被触发5次,你在代码中做错了什么。

答案 4 :(得分:9)

我认为您添加了五次点击事件。 试着算一下你做了多少次。

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

答案 5 :(得分:7)

这应该解决它,应该是一个好习惯:.unbind()

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

答案 6 :(得分:6)

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

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

    //your code here

 });

然后,如果您需要在其他元素中执行某些操作,同时点击其中一个,则可以遍历这些元素:

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

      //your code here
     }
  );
 }
);

答案 7 :(得分:5)

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

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

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

答案 8 :(得分:4)

我遇到了同样的问题。 在我看来,PHP代码生成了几次相同的jQuery代码,这就是多重​​触发器。

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

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

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

我的解决办法是将另一个php文件中的脚本分开,然后一次加载该文件。

答案 9 :(得分:2)

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

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

答案 10 :(得分:1)

我在自己的项目中亲自尝试过。

表格中的所有行都有一个类&#34;联系&#34;:

All my rows in a table have a class "contact".

我的代码如下所示:

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 console screenshot after code execution

但后来我意识到点击事件没有被触发,因为没有出现警告对话框。 Firebug只显示受点击覆盖影响的元素。所以没什么可担心的。

答案 11 :(得分:1)

尝试使用<input type="checkbox" name="rf538" id="rf538" class="page_checkbox"> <label for="rf538"><span></span>Pleasures</label>处理程序:

.off()

我在OK模式按钮上附加了一个click事件处理程序,以便对具有类$(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.. } 的对象的click事件进行操作。

在第一次单击时,事件仅在我要求函数执行的.archive-link对象上触发(.archive-link)。但是当我第二次点击相同的链接并在模态上点击OK时,事件将触发我之前点击的var linkObj的每个对象。

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

答案 12 :(得分: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元素将仅被声明一次。因此,如果您单击该元素,则只会触发一次。

答案 13 :(得分:0)

我遇到了同样的问题。 原因是我有几次同样的jquery。他被安置在一个循环中。

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

因此被多次开枪

答案 14 :(得分:0)

只需在下面的代码中进行操作就可以了

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


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

}

答案 15 :(得分: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>

答案 16 :(得分: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>

答案 17 :(得分:0)

我发现,当我使用 javascript 创建多个重复元素并在页面加载时将它们注入 HTML 时,Jquery .click() 不起作用。

在这种情况下,在 javascript 中生成元素时,将 onClick 标记附加到 html 元素

$("#items").html('<button onClick="delete_item(`'+item+'`)" value="'+item+'">Remove</button>');

然后,当你点击这个按钮时,它会执行delete_item()函数并将this传递给它以备后用。

function delete_item(item){

    console.log(item);

}

答案 18 :(得分:-5)

您的活动仅触发一次...... 所以这段代码可能有效 试试这个

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