我的目标是绑定到页面上的许多元素(使用 on()),然后在单击特定元素后取消绑定(使用 off())。
$(document).on({
mouseenter: enter,
mouseleave: leave,
mousedown: down,
mouseup: up,
click: click
}, ".up_side .thumbsUp");
on() 函数运行良好,但我不知道如何使用 off() 解除与单击元素的绑定。
var click = function() {
var thumbsUp = $(this);
var successCallback = function(data) {
// This is where I need to unbind the clicked element
$(thumbsUp).off({
mouseenter: enter,
mouseleave: leave
});
}
$(this).castVote(direction, modelName, modelId, successCallback, errorCallback);
}
谢谢!!!
解决方案
使用 .data() 存储标志并在执行代码之前检查标志。这似乎是一种解决方法,并使代码更脆弱。如果有人找到更好的方法,请回帖。谢谢!
$(document).on({
mouseenter: function(){
if ($(this).data("submitted") != true)
{
$(this).css("cursor", "pointer");
$(this).css("backgroundPosition", "-48px");
}
},
mouseleave: function(){
if ($(this).data("submitted") != true)
{
$(this).css("backgroundPosition", "0px");
}
},
mousedown: function() {
if ($(this).data("submitted") != true)
{
$(this).css("backgroundPosition", "-96px");
}
},
mouseup: function() {
if ($(this).data("submitted") != true)
{
$(this).css("backgroundPosition", "0px");
}
},
click: function() {
if ($(this).data("submitted") != true)
{
var thumbsUp = $(this);
var ballotBox = $(thumbsUp).parent();
var votingStation = $(ballotBox).parent();
//ballotBox.hide(0, "", function() {
var direction = $(thumbsUp).dataset("direction");
var modelName = $(votingStation).dataset("modelName");
var modelId = $(votingStation).dataset("modelId");
var successCallback = function(data) {
$(thumbsUp).css("backgroundPosition", "-144px");
// Add flag to indicate successful vote
thumbsUp.data("submitted", true)
$(this).vote_up_side('animateBallotBox', data, ballotBox, thumbsUp);
}
var errorCallback = function(XMLHttpRequest, textStatus, errorThrown) {
$(this).vote_up_side('animateError', ballotBox);
}
$(this).castVote(direction, modelName, modelId, successCallback, errorCallback);
}
}
}, ".up_side .thumbsUp");