Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying a .click() function for multiple HTML elements and changing context

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.

like image 360
AlwaysNeedingHelp Avatar asked Feb 14 '23 18:02

AlwaysNeedingHelp


2 Answers

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 );
like image 143
Rajaprabhu Aravindasamy Avatar answered Feb 16 '23 07:02

Rajaprabhu Aravindasamy


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');
});
like image 41
Felix Avatar answered Feb 16 '23 08:02

Felix