Multiple identifiers in a single JavaScript click event

In JavaScript, I use the click event to modify chart data. The following is the click event method.

$('#pro1').click(function () { chart.series[0].update({ data: pro1 }); }); $('#pro2').click(function () { chart.series[0].update({ data: pro2 }); }); $('#pro3').click(function () { chart.series[0].update({ data: pro3 }); }); 

I need to minimize these three click events in a single event, which means I want to write a single click event that processes identifiers. something like the code below.

 $('#pro'+i).click(function () { chart.series[0].update({ data: pro+i }); }); 


I do not know how to do that. The above code is incorrect, it's just a lack of JavaScript knowledge.

+7
javascript jquery event-handling click
source share
6 answers

I would suggest creating an object and selecting elements using classes, the id element that clicked gets the value of the corresponding property of the auxiliary object:

 var pros = { pro1: '...', pro2: '...' }; $('.pros').click(function () { chart.series[0].update({ data: pros[this.id] }); }); 
+8
source share

Try the following:

 var that = this; $('#pro1,#pro2,#pro3').click(function () { chart.series[0].update({ data: that[$(this).attr('id')]; }); }); 
+30
source share
 $('#pro1,#pro2,#pro3').click(function () { chart.series[0].update({ data: $(this).attr('id'); }); }); 

Updated Code

 $('#pro1,#pro2,#pro3').click(function () { chart.series[0].update({ data: window[this.id] }); }); 
+7
source share

Use class.

 $('.pro').click(function () { chart.series[0].update({ data: $(this).attr('id'); }); }); 

And then on each of the elements # pro1, # pro2, # pro3 add the class 'pro'

+3
source share
 $("*[id^=pro]").click(function () { chart.series[0].update({ data: $(this).attr('id'); }); }); 
+2
source share

You can give all your elements a class name and use the selector: eq () in jQuery.

0
source share

All Articles