第二次单击后jQuery不运行函数(animate,css),但console.log有效吗?
我有这个代码:
$('.navigation a').on('click', function() { $('.navigation').mouseleave(function() { $('.navigation a').not('.bold').delay(2000).animate({opacity : 0}, 800, (function(){ $(this).css({'visibility': 'hidden'}); })); }); $('.navigation').mouseenter(function() { $('.navigation a').css({visibility: 'visible'}); $('.navigation a').animate({opacity : 1}, 800); console.log('asdfasd'); }); });
html:
当我单击一次,代码工作,在第二次单击后,
.mouseenter
函数与.animate()
和.css()
不再工作,但console.log()
运行。 为什么?在此处将其视为示例: http : //liebdich.biz/ 。
每次单击时,都会为mouseenter和mouseleave添加事件处理程序的新副本,以便您可以同时运行多个副本。 那会引起问题。
如果您描述了您要实现的目标并显示相关的HTML,我们可能会建议一种正确的方法来执行此操作。
如果您只想在第一次单击时启动该行为,那么您可以执行以下操作:
$('.navigation a').on('click', function() { // get the navigation parent var parent = $(this).closest('.navigation'); // check to see if the event handlers have already been installed if (!parent.data("handlersInstalled")) { parent.mouseleave(function() { $('.navigation a').not('.bold').stop(true).delay(2000).animate({opacity : 0}, 800, function(){ $(this).css({'visibility': 'hidden'}); }); }).mouseenter(function() { $('.navigation a').css({visibility: 'visible'}); $('.navigation a').stop(true).animate({opacity : 1}, 800); console.log('asdfasd'); }); // mark that we've installed handlers parent.data("handlersInstalled", true); } });
我在这里做了几处改动:
- 事件处理程序仅在每个对象上安装一次
- 它们只安装在我们点击的项目的父项上(不是apge中的所有项目)
- 我在动画中添加了
.stop()
,因此如果快速移动鼠标,动画就不会堆积起来- 使用事件链接在同一个jQuery对象上调用多个方法