Javascript 如何解除jquery中使用一种方法附加的事件的绑定?
假设我有以下标记:Javascript 如何解除jquery中使用一种方法附加的事件的绑定?,javascript,jquery,Javascript,Jquery,假设我有以下标记: <div class="button">1</div> <div class="button">2</div> <div class="button">3</div> <div class="button">4</div> 问题是一个事件附加到所有四个按钮。所以,如果我在第一个按钮上鼠标悬停,然后再在第一个按钮上鼠标悬停,那么一切都会好起来,但如果我在第一个按钮上鼠标悬停后再在第
<div class="button">1</div>
<div class="button">2</div>
<div class="button">3</div>
<div class="button">4</div>
问题是一个事件附加到所有四个按钮。所以,如果我在第一个按钮上鼠标悬停,然后再在第一个按钮上鼠标悬停,那么一切都会好起来,但如果我在第一个按钮上鼠标悬停后再在第二个按钮上鼠标悬停,那么一个方法会再次被触发。如果我能做到这一点:
$(".button").one('mouseenter', function() {
console.log("A button was pressed for the first time")
$(".button").on('mouseenter', function(){
console.log("One button has already been pressed once")
})
//Remove event attached with one method from all buttons
});
这样,一个方法不会触发多次。但jquery表示,附加在方法上的事件只能被删除
那么,有没有任何方法可以解除jquery中使用一种方法附加的事件的绑定?在这里对您没有任何帮助,尽管使用它是无害的
您可以删除与one
挂钩的处理程序,就像删除与之挂钩的处理程序一样:使用相同的事件和相同的处理程序调用(或使用事件名称空间等)
因此,在您的情况下,最简单的事情可能是:
function handleOnce() {
console.log("A button was pressed for the first time")
$(".button").off('mouseenter', handleOnce) // <===
.on('mouseenter', function(){
console.log("One button has already been pressed once")
})
}
$(".button").on('mouseenter', handleOnce);
函数handleOnce(){
console.log(“第一次按下按钮”)
$(“.button”).off('mouseenter',handleOnce)/无需使用.one
附加事件。以下代码将适用于每个按钮,在其回调中,您可以在鼠标输入时应用逻辑
$(".button").on('mouseenter', function(){
$(this) // is the button that was pressed
})
是否有删除事件的原因?我不明白为什么上面的代码不适合您的情况
如果您只希望应用事件和以下逻辑,可以这样解除绑定:
$(".button").on('mouseenter', function(){
$(this) // is the button that was pressed
// your logic here
$(this).unbind('mouseenter')
})
我使用了one
,因为我想在第一次悬停时做一些特别的事情,然后在其他悬停事件之后再做同样的事情。@user31782:是的,这对单个元素非常有效,但对一组元素则不行,因为“一次”-它的特性是基于每个元素的。但是现在使用你的方法,如果我从所有按钮中删除one
,那么它应该工作得很好。那么你为什么说one对你没有任何帮助呢?@user31782:因为one
的特性(与上的相反)不要帮助你尝试做什么。我认为的另一种方法是var-alreadyHovered=0;
并在mousenter事件上将其设置为1
,以记录事件是第一次触发还是第二次触发。不,one
没有被弃用。这不像。我一定是把它错当成了另一个函数,我没有使用jQuery一个函数虽然
$(".button").on('mouseenter', function(){
$(this) // is the button that was pressed
// your logic here
$(this).unbind('mouseenter')
})