问题 等待Javascript模式的“返回值”


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

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

题 :

  • 内在逻辑应该是什么?

我的意思是 :

  • 用户点击buttonA(最终执行actionA)
  • 我想启动模态,等待输入(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 消息和是'href to javascript:functionToExec
  • 说得通?

我知道这可能听起来有点令人困惑 - 但我根本不知道最友好的javascript方式是什么...


5111
2017-08-13 09:53


起源



答案:


我创建了一个围绕模态的对话管理器 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"

这是一个小提琴,有一个简单的对话管理器示例

请注意,如果您正在使用 Bootstrap 3,你应该添加一个处理程序 hidden.bs.modal 事件而不是 hidden


11
2017-08-13 10:03



非常感谢!那非常有帮助! ;-) - Dr.Kameleon
you should make both the Cancel and Yes button  - 如果在事件处理程序中停止事件传播,这可能不起作用。在那种情况下,使用 modal('hide') 点击是。 - user


答案:


我创建了一个围绕模态的对话管理器 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"

这是一个小提琴,有一个简单的对话管理器示例

请注意,如果您正在使用 Bootstrap 3,你应该添加一个处理程序 hidden.bs.modal 事件而不是 hidden


11
2017-08-13 10:03



非常感谢!那非常有帮助! ;-) - Dr.Kameleon
you should make both the Cancel and Yes button  - 如果在事件处理程序中停止事件传播,这可能不起作用。在那种情况下,使用 modal('hide') 点击是。 - user


使用jquery,您可以使用类似的东西

$('.btn').click(function(){
   val=$(this).val()
   if(val=='Yes'){
     //continue the processing
   }
})

1
2017-08-13 10:06