【问题标题】:Stop function until clicked ok or cancel - JQUERY停止功能,直到单击确定或取消 - JQUERY
【发布时间】:2017-03-09 15:11:24
【问题描述】:

我创建了这样的自定义确认框:

function formPopup(message, callback) {
    message = message + '<div class="clear"></div><button class="mybutton" name="check" value="true">Yes</button>' +
            '<button class="mybutton mybutton2" name="check" value="false">No</button>';
    createPopup("Message", message);

    $(".popup .body button[name='check']").bind("click", function (e) {
        val = $(this).val();
        if (val == "true") {
            $(".popup").find(".close").trigger("click");
            typeof (callback) != "undefined" ? callback() : null;
        } else {
            $(".popup").find(".close").trigger("click");
        }
    });
}

我希望当我运行 formPopup 函数时,页面会像“确认”或“警报”一样等待,直到我点击 $(".popup .body button[name='check']")

我试过了

promise and when

但它没有帮助。

很多

【问题讨论】:

  • 弹出窗口是否显示?
  • 使用像Sweet Alert这样的自定义警报库可能会简单得多
  • 不可能像alertprompt 那样同步等待formPopup。你必须使你的代码异步。向我们展示您是如何尝试使用 Promise 的。

标签: javascript promise confirm


【解决方案1】:

你的意思是这样的吗?

jQuery 无法在您的点击功能中获取“this”,我将其替换为 e.target,因此 event.target == 您正在点击的按钮。

function showPopup(message, callback) {
    $(".popup").css("display", "block");
    $(".title").html(message);
    
    // only button 1, value will be true anyways, but just to show how to access the button object
    $(".b1").on("click", (e) => {
        var val = $(e.target).val();
        if (val == "true") {
          closePopup();
          typeof (callback) != "undefined" ? callback() : null;

        } else {
          closePopup();
        }
    });
    
    // button 2, try to split as much as you can, makes everything alot easier
    $(".b2").on("click", (e) => {
       closePopup();
    });
}

function closePopup() {
    $(".popup").css("display", "none");
    setTimeout(() => {
      showPopup("back again", () => { console.log("callback"); });
    }, 2000);
}

showPopup("message", () => { console.log("callback"); });
.popup {
  position: fixed;
  display: none;
  left: 0;
  top: 0;
  bottom: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.2);
  z-index: 1;
}

.popup-content {
  position: absolute;
  color: red;
  background: green;
  width: 300px;
  left: calc(50% - 150px);
  height: 100px;
  top: calc(50% - 50px);
  z-index: 2;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="clear">
</div>
<div class="popup">
  <div class="popup-content">
    <h1 class="title"></h1>
    <button class="b1" name="check" value="true">Yes</button>
    <button class="b2" name="check" value="false">No</button>
  </div>
</div>

【讨论】:

    猜你喜欢
    • 2023-03-19
    • 2012-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-23
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    相关资源
    最近更新 更多