【问题标题】:Wait for "return value" from Javascript modal等待来自 Javascript 模式的“返回值”
【发布时间】:2012-08-09 12:58:48
【问题描述】:

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

  • 我正在使用Twitter Bootstrap's Modals
  • 在某些情况下,在执行操作之前,我想通过“您确定吗?”来验证它。 (是/否)模式对话框。

问题:

  • 内部逻辑应该是什么?

我的意思是:

  • 用户点击 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 设置为消息并将Yes' href 设置为javascript:functionToExec
  • 有意义吗?

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

【问题讨论】:

    标签: javascript jquery html twitter-bootstrap modal-dialog


    【解决方案1】:

    我围绕模态创建了一个对话框管理器,使用 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

    【讨论】:

    • 非常感谢!这很有帮助! ;-)
    • you should make both the Cancel and Yes button - 如果您在事件处理程序中停止事件传播,这可能不起作用。在这种情况下,请在单击“是”时使用 modal('hide')
    【解决方案2】:

    使用 jquery 你可以使用类似的东西

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

    【讨论】:

      猜你喜欢
      • 2012-11-07
      • 2016-10-16
      • 2020-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多