Multiple id's in a single JavaScript click event

前端 未结 7 585
生来不讨喜
生来不讨喜 2020-12-14 19:23

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

$(\'#pro1\').click(function () {
            chart.series[0].up         


        
相关标签:
7条回答
  • 2020-12-14 19:29

    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'

    0 讨论(0)
  • 2020-12-14 19:38

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

    0 讨论(0)
  • 2020-12-14 19:42
    $('#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]
        });
    });
    
    0 讨论(0)
  • 2020-12-14 19:44

    Try this:

    var that = this;
    $('#pro1,#pro2,#pro3').click(function () {
        chart.series[0].update({
            data: that[$(this).attr('id')];
        });
    });
    
    0 讨论(0)
  • 2020-12-14 19:45

    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]
        });
    });
    
    0 讨论(0)
  • 2020-12-14 19:46
    $("*[id^=pro]").click(function () {
        chart.series[0].update({
             data: $(this).attr('id');
        });
    });
    
    0 讨论(0)
提交回复
热议问题