单个 JavaScript 点击事件中的多个 id

2022-01-15 00:00:00 event-handling jquery click javascript

在 JavaScript 中,我使用点击事件来更改图表数据.下面是点击事件的方法.

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
            });
        });

我需要在一个事件中缩小这三个点击事件,这意味着我想编写一个处理 id 的点击事件.类似于下面的代码.

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
});
});


我不知道该怎么做.上面的代码不正确,只是我对 JavaScript 的了解不够.


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

推荐答案

我建议创建一个对象并使用类选择元素,点击元素的 id 检索相应属性的值辅助对象:

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]
    });
});

相关文章