Jquery class 选择器点击重复功能

Jquery class selector click repeat function

我有一个 class 选择器绑定了点击。当我点击多次时出现问题,第一次调用两次,下一次调用三次,依此类推。

var point = data.points[0].x;
    var counter = 0;          
    $(".menuOption").click(function () {
        console.log(counter);
        counter++;    
        var code = $(this).attr('id');
        var text = $(this).html();
        var newLine = {
            type: 'line',
            x0: point,
            x1: point,
            y0: 0,
            y1: 1,
            yref: 'paper',
            line: {
                color: 'black',
                width: 1
            },
            name: text
        };
        var annotation = {
            x: point,
            y: data.points[0].y,
            xref: 'x',
            yref: 'y',
            text: code,
            textangle: 90,
            showarrow: true,
            arrowhead: 7
        }
        Plotly.relayout("grap", {
            'shapes[0]': newLine,
            'hovermode': 'closest',
            'annotations[0]': annotation
        });

    });    

我在下面的笔里加了一些console.log

CodePen

在第 76 行,您正在设置点击侦听器:

myPlot.on('plotly_click', function (data) { ... }

在该处理程序中(第 106 行),您正在菜单选项上设置另一个点击侦听器:

$(".menuOption").click(function () { ... }

所以每次 plotly_click 事件发生时,您都在添加另一个点击侦听器。您可能应该将 menuOption click 侦听器的绑定移动到事件处理程序之外,或者您应该在设置新侦听器之前解除绑定。