我使用 Jquery 和 ajax。 我在单击、取消绑定(bind)后和ajax绑定(bind)单击后执行操作。 但绑定(bind)方法不起作用。 请帮助我
$(".lang").on("click", function (e) {
$(this).unbind('click');
if ($(this).hasClass("disabledLanguage")) {
return false;
}
var token = $('[name=__RequestVerificationToken]').val();
$.ajax({
type: "POST",
url: Host + "Language",
data: { __RequestVerificationToken: token, Code: $(this).data("code") },
success: function (data) {
if (data.IsCompleted) {
//window.location = window.location.href;
}
else {
//alert("Error");
}
$(this).unbind('click'); //<----Notworking
}
});
return false;
});
最佳答案
/**
* make a function to handle the click event stand alone
* it's good for reuse and test
*/
function clickHandler(e){
/**
* cache the result of $(this)
* for performance and reuse in another function context
*/
var $lang = $(this);
$lang.unbind('click', clickHandler);
if ($lang.hasClass("disabledLanguage")) {
return false;
}
var token = $('[name=__RequestVerificationToken]').val();
$.ajax({
type: "POST",
url: Host + "Language",
data: { __RequestVerificationToken: token, Code: $lang.data("code") },
success: function(data) {
if (data.IsCompleted) {
//window.location = window.location.href;
} else {
//alert("Error");
}
/**
* doing after click,unbind and after ajax bind click
* so it should be bind click but not unbind click
*/
$lang.bind('click', clickHandler);
}
});
return false;
}
$(".lang").on("click", clickHandler);
也许这可以帮助你,评论中有更多详细信息
关于javascript - Ajax 绑定(bind)事件后不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42476607/