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

我在一个同名的页面上有多个类。然后我有一个。在我的 JS 中的 click ()事件。我想要发生的是点击事件只发生一次,不管我的页面上有多个类。

场景是我使用 AJAX 添加到购物车。有时在主页上可能会有一个特色产品和一个最高报价,这意味着同一类。加。# 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});
707748 次浏览

when you click div with addproduct class one event is fired for that particular element, not five. you're doing something wrong in you code if event is fired 5 times.

Could we see your click handler? You're attaching 5 listeners to 5 different elements. However, when the user clicks on the element, only one event is fired.

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


addToCart(productId);
});

If this solution doesn't work I'd like to look at your click handler.

I think you add click event five times. Try to count how many times you do this.

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

I had the same problem. The cause was that I had the same jquery several times. He was placed in a loop.

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

For this reason was firing multiple times

I just had the same problem. In my case PHP code generated few times the same jQuery code and that was the multiple trigger.

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

(PHP MULTIPLE GENERATER NUMBERS generated also the same code multiple times)

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

My solution was to separate script in another php file and load that file ONE TIME.

I solved it by using inline jquery function call like

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


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

your event is triggered only once... so this code may work try this

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

I tried it myself in my project.

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

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

My code looks like this:

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

And I was first scared to see my whole rows as a result in the Firebug console when I executed the code:

Firebug console screenshot after code execution

But then I realized that the click event was not fired, because no alert-dialog appeared. Firebug shows you just the elements which are affected by the click overiding. So there is nothing to worry.

This should fix it and should be a good habit: .unbind()

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

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.StopPropagation and event.StopImmediatePropagation() should do the trick.

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() 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.

Sources: https://api.jquery.com/event.stoppropagation/ https://api.jquery.com/event.stopimmediatepropagation/

Simply enter code hereIn JQuery, ones event is triggered you just check number of occurrences of classes in file and use for loop for next logic. for identify number of occurrences of any class, tag or any DOM element through JQuery : var len = $(".addproduct").length;

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

In this situation I would try:

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


//your code here


});

then, if you need to perform something in the other elements with the same class on click on one ot them you can loop through the elements:

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


//your code here
}
);
}
);

Try making use of the .off() handler:

$(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..
}

I attach a click event handler on an OK modal button to act on click event of the object with class .archive-link.

On the first click, the event fires only on that .archive-link object that I asked the function to act on (var linkObj). But when I click the same link the second time and hit OK on the modal, the event fires on every object that has .archive-link that I clicked before.

I used the solutions above but unfortunately did not work. It was when I called .off() within the modal OK button click function that the propagation stopped. I hope this helps.

This question have been resolved and also got a lot of responses, but i want to add something to it. I was trying to figure out, why my click element his firing 77 times, and not one time.

in my code, i had an each, running a json response and displaying it as divs with buttons. And then i declared the click event inside the each.

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


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

If you write your your code like this, the class .test-button will get multiple click events. For example, my data has 77 lines, so the each will run 77 times, that means i will decline the click event on the class 77 times. When you click the element, it will be fired 77 times.

But if you wirte it like this:

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


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

you are declaring the click element after the each. That means, the each will run its 77 times, and the click element will be declared only one time. So, if you click the element, it will be fired only one time.

Just do below code it's working absolute fine

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




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


}

Hi sorry for bump this post just face this problem and i would like to show my case.

My code look like this.

<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 code

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


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

$(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>

I have found, when I am creating multiple duplicate elements with javascript and inject them into the HTML on page load, Jquery .click() does not work.

In this case, attach an onClick tag to the html element when you generate the element in javascript

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

Then later, when you click this button, it will execute the delete_item() function and pass this into it for use later.

function delete_item(item){


console.log(item);


}

class name denoted by dot(.) and click method will trigger when you will click on where you given class name addproduct.

$(".addproduct").click(function(){
//your logic on click
console.log("clicked");
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<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>