gpt4 book ai didi

javascript - 等待来自 Javascript 模态的 "return value"

转载 作者:技术小花猫 更新时间:2023-10-29 12:52:06 25 4
gpt4 key购买 nike

好吧,我绝不是 JavaScript 大师,也许我还在考虑桌面软件开发,但这就是我想要实现的目标:

  • 我正在使用 Twitter Bootstrap's Modals
  • 在某些情况下,在采取行动之前,我想用“你确定吗?”来验证它。 (是/否)模态对话框。

问题:

  • 内部逻辑应该是什么?

我的意思是:

  • 用户点击按钮 A(最终执行操作 A)
  • 我想启动模式,等待输入(2 个按钮之一 - 是/否)和/或在执行(或不执行)actionA 之前将其传递给某个检查例程

这是我的模态 HTML 代码(按钮是否应该 - 以某种方式 - 通过它们的 onclick javascript 例程起作用?) - 还要注意 #confirmMessage 将是变量。

<div class="modal fade hide" id="confirmAlert">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">x</button>
<h3 id="confirmTitle">Are you sure?</h3>
</div>

<div class="modal-body">
<p id="confirmMessage">Body</p>
</div>
<div class="modal-footer">
<a href="#" class="btn" data-dismiss="modal">Cancel</a>
<a href="#" class="btn btn-danger">Yes</a>
</div>
</div>

只是一个想法:

  • 写一个像checkBeforeExec(message,functionToExec)这样的函数
  • #confirmMessage 设置为消息,将 Yes 的 href 设置为 javascript:functionToExec
  • 有道理吗?

我知道这听起来有点令人困惑 - 但我只是不知道这样做对 JavaScript 最友好的方法是什么......

最佳答案

我围绕模态创建了一个对话框管理器,使用 confirm 辅助函数来执行以下操作:

var callback = function(result) {
alert(result);
}); // define your callback somewhere

$('#confirmAlert').on('click', '.btn, .close', function() {
$(this).addClass('modal-result'); // mark which button was clicked
}).on('hidden', function() {
var result = $(this).find('.modal-result').filter('.btn-danger').length > 0; // attempt to filter by what you consider the "YES" button; if it was clicked, result should be true.

callback(result); // invoke the callback with result
});

此外,您应该同时制作取消和是按钮 data-dismiss="modal"

Here's a fiddle, with a simple example of my dialog manager .

请注意,如果您使用的是 Bootstrap 3,则应将处理程序添加到 hidden.bs.modal 事件而不是 hidden .

关于javascript - 等待来自 Javascript 模态的 "return value",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11931906/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com