本文介绍了如何正确使用jQuery off()方法从某个元素上删除mouseenter和mouseleave事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我似乎在使用jQuery off()方法从元素中删除某些事件时遇到了一些麻烦.当我符合特定条件时,我想删除mouseenter和mouseleave事件.
I seem to be having some trouble removing some events from an element using the jQuery off() method. I want to remove the mouseenter and mouseleave events when I match a certain criteria.
这是我得到的.
jsfiddle: http://jsfiddle.net/GE7Wg/
jsfiddle: http://jsfiddle.net/GE7Wg/
在上面的提琴演奏中,第2条不应有与之相关的mouseenter/mouseleave事件.
On the above fiddle, Article 2 should NOT have a mouseenter/mouseleave event associated with it.
谢谢!
<!DOCTYPE html>
<html>
<head></head>
<body>
<input type="hidden" id="HiddenMediaID" value="450">
<article class="Article">
Article 1
<input type="hidden" class="LatestMediaID" value="200" />
</article>
<article class="Article">
Article 2
<input type="hidden" class="LatestMediaID" value="450" />
</article>
<article class="Article">
Article 3
<input type="hidden" class="LatestMediaID" value="700" />
</article>
</body>
</html>
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操作并抛出一些条件
Lets do some DOM manipulations and throw some conditions
//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');
}
});
});
这篇关于如何正确使用jQuery off()方法从某个元素上删除mouseenter和mouseleave事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!