Jquery 等待事件返回值

标签 jquery

我编写了一个函数用作确认框:

$.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/

相关文章:

jquery - 分页在 IE 中无法正常工作(仅加载第一项)

javascript - 删除元素上的事件监听器的最佳方法是什么?

jquery - 从右到左悬停 div 的按钮 Onclick 在我的 JSP 页面上不起作用。

javascript - 从 div 中删除特定文本

javascript - 如何将方法附加/扩展到 dom 元素

javascript - jQuery 删除多个输入然后只添加一个

javascript - 从文本链接启动 jPlayer

javascript - jQuery FileUpload 发送的文件数据在哪里?

jquery - 在不更改类的情况下使用 jquery 更改 css

jquery - 你能在 jquery 模态对话框中提交表单吗