2012-01-24 34 views
2

我将一个mouseenter/mouseleave事件绑定到一个元素(仅仅是一个图像),然后执行两个函数。我的问题是,我希望这两个函数中的一个只在第一个mouseenter上触发一次。jQuery两个mouseenter事件,触发一个函数ONCE

aka在第一个mouseenter上发生了两件事,在第二件mouseneter上只发生了一件事。

$(.bubbles).mouseenter(function(){ 
    functionSwapImage();       //this should happen everytime 
}).mouseleave(function(){ 
    functionSwapImageBack();      //this should happen everytime 
    $(".bubbles").one("mouseleave", function(){ 
     myFunction();       //this should happen once! 
    }); 
}); 

编辑:http://jsfiddle.net/Am5ZC/

如果我移动.one功能块之外,进入它自己单独的鼠标进入/离开块,那么functionSwapImageBack()只能触发一次(即。一是删除事件对于这两个代码块)。

不太清楚该怎么做,但感谢您的帮助!

回答

1

尝试使用名称空间事件,该名称空间事件只删除具有名称空间的特定事件处理程序。

$(".bubbles").mouseenter(function(){ 
    functionSwapImage();       //this should happen everytime 
}).mouseleave(function(){ 
    functionSwapImageBack();      //this should happen everytime 
}).one("mouseleave.onlyonce", function(){ 
    myFunction();       //this should happen once! 
}); 
+0

看起来不错,但你需要移动块外的'one'功能。否则每当鼠标离开时它都会被绑定 –

+0

我是否必须编辑html?我该如何处理“onlyonce”命名空间?即'myFunction(){console.log(“good”); }'应该是什么样子? – jaredrada

+0

@BrianGlaz - 不错的点就错过了。 – ShankarSangoli

1

这应该工作:

$('.bubbles').one('mouseleave', myFunction) 
.mouseenter(functionSwapImage) 
.mouseleave(functionSwapImageBack); 

不知道,如果你想将它绑定到mouseleavemouseenter事件。

更新:它似乎在jQuery 1.7正常工作,但不在jQuery 1.7.1。这似乎是一个错误。

+0

谢谢你felix king =] – jaredrada