如何正确使用jQuery off()方法从元素中删除mouseenter和mouseleave事件

我似乎在使用jQuery off()方法从元素中删除一些事件时遇到了一些麻烦。 我想在符合特定条件时删除mouseenter和mouseleave事件。

这是我得到的。

jsfiddle: http : //jsfiddle.net/GE7Wg/

在上述小提琴中,第2条不应该有与之关联的mouseenter / mouseleave事件。

谢谢!

HTML

     
Article 1
Article 2
Article 3

jQuery的

 //Page loaded - jQuery Ready $(document).ready(function () { //User hovering over article. Change BG. $(document).on('mouseenter', '.Article', function () { $(this).css('background', '#F0F8FF'); }).on('mouseleave', '.Article', function () { $(this).css('background', '#FFFFFF'); }); //Set active BG color if condition is met. $('.LatestMediaID').each(function () { var LatestMediaID = $(this).val(); //Disable mouseenter and mouseleave events on the matched Article. if (LatestMediaID == $('#HiddenMediaID').val()) { //Disable events. $(document).off('mouseenter', $(this).parent()); $(document).off('mouseleave', $(this).parent()); //Change BG color to light blue. $(this).parent().css('background', '#F0F8FF'); } }); }); 

CSS

 .Article { width: 150px; height: 35px; line-height: 35px; margin: 10px; background-color: #FFFFFF; border: 1px solid #CCCCCC; text-align: center; } 

让我们做一些DOM操作并抛出一些条件

 //Page loaded - jQuery Ready $(document).ready(function () { //User hovering over article. Change BG. $(document).on('mouseenter', '.Article', function () { if( !( $(this).hasClass('donotSelect') ) ) $(this).css('background', '#F0F8FF'); else $(document).off('mouseleave', $(this)); }).on('mouseleave', '.Article', function () { if( !( $(this).hasClass('donotSelect') ) ) $(this).css('background', '#FFFFFF'); else $(document).off('mouseenter', $(this)); }); //Set active BG color if condition is met. $('.LatestMediaID').each(function () { var LatestMediaID = $(this).val(); //Disable mouseenter and mouseleave events on the matched Article. if (LatestMediaID == $('#HiddenMediaID').val()) { $(this).parent().addClass("donotSelect"); //Change BG color to light blue. $(this).parent().css('background', '#F0F8FF'); } }); }); 

http://jsfiddle.net/GE7Wg/5/

不确定是什么导致了这个问题,但你可以通过预先检查值来避免首先添加事件。

也许使用类似的东西:

 $(function() { var hidID = $("#HiddenMediaID").val(); $(".Article").each(function(){ var article = $(this); if(article.find(".LatestMediaID").val() !== hidID) { article.on("mouseenter", function(){ article.css("background", "#F0F8FF") }); article.on("mouseleave", function(){ article.css("background", "#FFFFFF") }); } }); }); 

有一种方法可以按照您想要的方式在所选的文章级别http://api.jquery.com/event.stopPropagation/上添加另一个事件,但是真的很难看。 通过CSS http://jsfiddle.net/liho1eye/GE7Wg/4/来处理这个问题更加清晰

 .selected, .hover { background-color:#F0F8FF;}​ 

脚本:

 $(document).on('mouseenter mouseleave', '.Article', function(e) { $(this).toggleClass("hover", e.type == "mouseenter"); });