Jquery类选择器单击重复函数



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

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

我在下面的笔中添加了一些控制台.log。

代码笔

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

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

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

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

因此,每次发生plotly_click事件时,您都会添加另一个单击侦听器。您可能应该将 menuOption 单击侦听器的绑定移到事件处理程序之外,或者应该在设置新侦听器之前取消绑定侦听器。

最新更新