我似乎在使用 jQuery off() 方法从元素中删除某些事件时遇到了一些麻烦。当我符合某个条件时,我想删除 mouseenter 和 mouseleave 事件。
这是我得到的。
jsfiddle:http: //jsfiddle.net/GE7Wg/
在上面的小提琴中,第 2 条不应有与其关联的 mouseenter/mouseleave 事件。
谢谢!
HTML
<!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;
}
</p>