【问题标题】:jQuery confirm / cancel home made function not workingjQuery确认/取消自制功能不起作用
【发布时间】:2014-09-21 09:02:47
【问题描述】:

我自己制作了是/否功能,但它不起作用。

函数如下:

function CoverAndShow (title, text, type) {
    if (type == "confirm") {
        $("body").append("<div class='msg'><h3>" + title + "</h3><p>" + text + "</p><input class='ok' type='button' value='OK' /><input type='button' class='cancel' value='Cancel' /></div>");
    }

    $(".ok").click(function() {
        return true;
    });

    $(".cancel").click(function() {
        return false;
    });
}

这是我在函数中单击“确定”的代码:

    $("#ask").click(function() {

    if (CoverAndShow("Title","Should I operate?", "confirm") == true) {
        alert("true");
    }

这不起作用,也不会返回任何东西。
非常感谢您的帮助!

【问题讨论】:

  • 哪一部分不行?
  • 应该是 === true
  • == 应该没问题,只要您不需要检查数据类型,不是吗?
  • @Undefined_variable,不,这也不起作用

标签: javascript jquery alert prompt


【解决方案1】:

您将需要在此处使用回调。你不能从这种函数中返回(查找异步)。您将一个函数作为最后一个参数传递给CoverAndShow,然后使用返回值调用它。

function CoverAndShow (title, text, type, callback) {
    if (type == "confirm") {
        $("body").append("<div class='msg'><h3>" + title + "</h3><p>" + text + "</p><input class='ok' type='button' value='OK' /><input type='button' class='cancel' value='Cancel' /></div>");
    }

    $(".ok").click(function() {
        callback(true);
    });

    $(".cancel").click(function() {
        callback(false);
    });
}

$("#ask").click(function() {

   CoverAndShow("Title","Should I operate?", "confirm", function(ret){
      if (ret) { // no need to explicitly check for true
         alert("true");
       }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="ask">ask</div>

【讨论】:

  • 我收到“意外的令牌返回”错误,你能解决这个问题吗?
  • 已修复。我使用新的 Stack Snippet 功能让您在答案中运行它。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-16
  • 2016-10-01
  • 2014-01-16
  • 2016-05-03
  • 1970-01-01
相关资源
最近更新 更多