Multiple id's in a single JavaScript click event

瘦欲@ 提交于 2019-11-27 02:16:28

问题


In JavaScript I am using click event to change chart data. Below is a method for click event.

$('#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 minify these three click events in one event, means I want to write one click event which handle the id's. some thing like below code.

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


I don't know how to do it exactly. The above code is not correct, it is just my lack of knowledge of JavaScript.


回答1:


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

var pros = {
   pro1: '...',
   pro2: '...'
};

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



回答2:


Try this:

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



回答3:


$('#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]
    });
});



回答4:


Use a class.

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

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




回答5:


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



回答6:


You could give all of your elements a class name and use the :eq() selector within jQuery.



来源:https://stackoverflow.com/questions/18508742/multiple-ids-in-a-single-javascript-click-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!