Applying .click () to multiple HTML elements and changing context

I am wondering if there is a way instead of listing what happens when each individual item is clicked, for example:

$('#object1').click(function(){ stuff += object1amount };
$('#object2').click(function(){ stuff += object2amount };
$('#object3').click(function(){ stuff += object3amount };
$('#object4').click(function(){ stuff += object4amount };
$('#object5').click(function(){ stuff += object5amount };

I can have:

$('LIST OF HTML ELEMENTS').click(function(){ stuff += this.amount };

where 'this' is the context of any HTML element that has been clicked.

+4
source share
6 answers

This kind of selector is called . In addition, you asked to support each html element with different data, so in this situation you can use less data with each html element to store a memory leak. Multiple selector .data()

Try it.

$('#object1,#object2,#object3,#object4,#object5').click(function(){
     stuff += $(this).data('amount');
};

To store data:

$('#sample').data( 'amount', 100 );
+2

amount data :

data-amount = "....."

:

$("[id^='object']").click(function() {
    stuff += $(this).attr('data-amount');
});
+2

:

var _this = this;

$("[id^='object']").click(function(){ stuff += _this.amount };
+1

, data-action=addAmount, . ..

$('.addAmount').click(...

$('[data-action=addAmount]').click(...
+1

class= "stuff"

$(".stuff").click(function()
{
stuff += this.amount;
});
+1

, objects ids are input type of text

var stuff = 0;
var objOnClick = function () {

    stuff += +this.value;
};
for (var i = 0; i < 4; i++) {

    document.getElementById('object' + (i + 1)).onclick = objOnClick;
};
+1

Source: https://habr.com/ru/post/1527259/


All Articles