ros*_*533 0 javascript jquery javascript-events
这是一个说明问题的小提琴.我在点击一个元素到'html'元素时添加一个jQuery one绑定.我不期望在下一次单击之前触发'one'事件处理程序,但它会在添加绑定的单击时触发.如果它是添加'one'事件处理程序的更具体元素,这似乎不是问题,但是当我使用'html'或'body'作为元素时会发生这种情况,这就是我想要做的事情.
这对我来说没有意义,我认为第一次点击会为下一次点击添加一个,并且不会点击链接上的点击.
顺便说一下,我的实际问题可能会以更好的方式解决,但我遇到了这个问题并且好奇为什么它没有像我预期的那样工作.
码:
HTML:
<div id='hello'>hello</div>
<a class="title" href="#">this example</a> is a test?
Run Code Online (Sandbox Code Playgroud)
JS:
$(function() {
$('a.title').click(function() {
var htmlClickBind = function (e) {
console.log('clicked on html, e.target = ' + e.target);
console.log(e.target == '');
if (!$(e.target).is('a') ) {
console.log('cleared click event');
}
else {
$('html').one('click', htmlClickBind);
}
};
$('html').one('click', htmlClickBind);
});
});?
Run Code Online (Sandbox Code Playgroud)
在click该事件a.target元素冒泡的html元素,你的(只添加)处理器看到它.
要防止这种情况,请event.stopPropgation在您的a.target click处理程序中使用(或者return false,使用stopPropagation和preventDefault).
更新的代码(请参阅注释):实时复制
$(function() {
// Accept the event arg ----v
$('a.title').click(function(e) {
// Stop propagation
e.stopPropagation();
var htmlClickBind = function (e) {
console.log('clicked on html, e.target = ' + e.target);
console.log(e.target == '');
if (!$(e.target).is('a') ) {
console.log('cleared click event');
}
else {
$('html').one('click', htmlClickBind);
}
};
$('html').one('click', htmlClickBind);
});
});?
Run Code Online (Sandbox Code Playgroud)