我编写了一个函数用作确认框:
$.fn.confirmation = function(message, color) {
$('.notification').css("background", color);
$('.notification').html(message + "<br/><a href='#' id='sure'>I am sure</a> or <a href='#cancel' id='cancel'>Cancel</a>");
$('.notification').slideDown();
$(document).on("click", '.notification a', function(event){
if($(this).attr("id") == "sure") {
$('.notification').slideUp();
return true;
} else if($(this).attr("id") == "cancel") {
$('.notification').slideUp();
return false;
}
});
};
我的问题是它总是返回 false,它甚至不等待 on 事件。
如何强制 JQuery 等待用户点击?
最佳答案
它不会返回 false
,而是返回 undefined
,因为您的 return 语句实际上是在事件发生时执行的匿名函数中,而不是在 确认
功能。 (在我看来)解决此问题的最简单方法是使用 deferred
对象:
$.fn.confirmation = function (message, color) {
$('.notification').css("background", color);
$('.notification').html(message + "<br/><a href='#' id='sure'>I am sure</a> or <a href='#cancel' id='cancel'>Cancel</a>");
$('.notification').slideDown();
var def = $.Deferred();
$(document).on("click", '.notification a', function (event) {
if ($(this).attr("id") == "sure") {
$('.notification').slideUp();
def.resolve(true);
} else if ($(this).attr("id") == "cancel") {
$('.notification').slideUp();
def.resolve(false);
}
});
return def.promise();
};
$.confirmation('message', 'red').done(function(result) {
// result is true or false.
});
关于Jquery 等待事件返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19381559/