我有一个嵌套的单击事件侦听器,我有一个问题,当我多次触发事件侦听器时,它们会被循环,并发送一个请求x2次数超过它应该。我的代码中的错误在哪里?这可能是一个初学者的错误,所以如果是这样,我非常抱歉。我还在学习JavaScript和jQuery。
代码:
$('body').on('click', '.color-pick-btn', function() {
id = $(this).data("highlight");
unique = $(this).data("unique");
$(".color-picker").show();
//show the menu directly over the placeholder
$(".color-picker").position({
my: "right top",
at: "right bottom",
of: this,
collision: "fit"
});
$('body').on('click', '.color-picker-item', function() {
color = $(this).data("color");
$.ajax({
type: "POST",
url: '/echo/json',
//data: "highlight=" + id + '&color=' + color + "&unique=" + unique,
data: {
json:'{"highlight":"id","color":"color","unique": "unique"}'
},
dataType: 'json',
}).done(function(data) {
console.log('test');
});
$(".color-picker").hide();
return false;
});
$(document).click(function(event) {
if (!(($(event.target).hasClass('color-pick-btn')) || ($(event.target).hasClass('color-picker-item')))) {
$(".color-picker").hide();
}
return false;
});
return false;
});JSFiddle地址:https://jsfiddle.net/o0r4z6g3/
查看控制台输出"test“。
干杯!
发布于 2020-01-20 03:47:11
您在每次调用事件侦听器时都添加了事件侦听器。我没有看过你的代码的意图,你也没有在你的答案中解释它,但这可能会解决你的问题。
$('body').on('click', '.color-pick-btn', function() {
// .position() uses position relative to the offset parent,
// so it supports position: relative parent elements
pos = $(this).offset();
id = $(this).data("highlight");
unique = $(this).data("unique");
// .outerWidth() takes into account border and padding.
width = $(this).outerWidth();
$(".color-picker").show();
//show the menu directly over the placeholder
$(".color-picker").position({
my: "right top",
at: "right bottom",
of: this,
collision: "fit"
});
return false;
});
$('body').on('click', '.color-picker-item', function() {
color = $(this).data("color");
$.ajax({
type: "POST",
url: '/echo/json',
//data: "highlight=" + id + '&color=' + color + "&unique=" + unique,
data: {
json: '{"highlight":"id","color":"color","unique": "unique"}'
},
dataType: 'json',
}).done(function(data) {
console.log('test');
});
$(".color-picker").hide();
return false;
});
$(document).click(function(event) {
if (!(($(event.target).hasClass('color-pick-btn')) || ($(event.target).hasClass('color-picker-item')))) {
$(".color-picker").hide();
}
return false;
});https://stackoverflow.com/questions/59813729
复制相似问题