I'm wondering if there is a way of instead of listing what happens when each individual element is clicked like:
$('#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 whatever HTML element was clicked.
This kind of selector is called as Multiple selector
. And additionally you asked to maintain each html elements with different data, so at that situation you can use .data()
to store memory leak less data with each html elements.
Try.
$('#object1,#object2,#object3,#object4,#object5').click(function(){
stuff += $(this).data('amount');
};
To store data:
$('#sample').data( 'amount', 100 );
If your element amount
is stored inside data
attribute like this:
data-amount = "....."
then you can use attributes starts with selector to achieve your task:
$("[id^='object']").click(function() {
stuff += $(this).attr('data-amount');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With