javascript - 避免多个 (40) jquery 确认对话框 - 重用?

标签 javascript jquery html css

我正致力于使用 jQuery 修复旧版 Web 应用程序。

我有一个包含 40 个按钮的表单,每个按钮都有某种使用 javascript 确认的确认类型。我想将它们切换为使用 jquery 模式对话框。

我已经对其中的几个进行了编程,如下所示,它们运行良好。问题是表单上有 40 个 - 所以不想编写 40 个单独的模式框。唯一真正改变的是单击"is"按钮时调用的 javascript

有什么建议吗?

在按钮上调用的代码:

$("#confirm1dialogTitle").html("Approve?");
$("#confirm1dialogText").html("Do you want to approve this request?");
$('#confirm1dialog').dialog('open');

嵌入式javascript:

<script type="text/javascript">
$(function() {
    $("#confirm1dialog").dialog({
        bgiframe: true,
        autoOpen: false,
        width: 350,
        height: 350,
        modal: true,
        buttons: {
            'Yes': function() {
                window.document.forms[0].FDDStatus.value = "Approved";
                window.document.forms[0].DivisionApproval.value = "Yes";
                window.document.forms[0].setApprovalFields();
            },
            'No': function() {
                $(this).dialog('close');
            }
        }
    });
});
</script>

嵌入式 HTML:

<div id="confirm1dialog" title="<span id='Title'>Title</span>">
   <div id="users-contain" class="ui-widget">
      <form>
         <span id="confirm1Text"></span>
      </form>
   </div>
</div>

最佳答案

您可以将正在更改的 javascript 放在一个函数对象中,然后重用它..

让我们假设你看起来像这样:

<form><input id='btn1' /><input id='btn2' /></form>

然后你做一个辅助函数:

var confirmHelper = function(id, yesCallback) {
  $(id).click(function() {
    $(function() {
      // the code from you example
      $("#confirm1dialog").dialog({
        bgiframe: true,
        autoOpen: false,
        width: 350,
        height: 350,
        modal: true,
        buttons: { 'Yes': yesCallback, 'No': function() { } }
      }
    }
  }
}

然后你将它应用到你的按钮上:

confirmHelper('btn1' function() {
  // your callback from before
  window.document.forms[0].FDDStatus.value = "Approved";
  window.document.forms[0].DivisionApproval.value="Yes";                                   
  window.document.forms[0].setApprovalFields();
});

confirmHelper('btn2' function() {
  // your other javascript code
});

像 40 个按钮一样:)

关于javascript - 避免多个 (40) jquery 确认对话框 - 重用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1415379/

相关文章:

javascript - 返回 JSON 响应到 ajax 调用提示下载包含响应的文件

javascript - 如何将服务器中的数据绑定(bind)到 Backbone.js 的模型

javascript - 让导航栏出现在白色背景的滚动条上

javascript - 直接链接到具有多个模态的开放模态

javascript - 为什么我不能在禁用文档后重新启用文档中的元素?

javascript - 在客户端 Node.js 中包含 JQuery

javascript - 在 AppleScript 和 JavaScript 中循环列表

javascript - 更新 MongoDB 数组中的多个值

javascript - 在哪里删除 forEach 循环/函数中的 null 元素?

javascript - AngularJs 动态更新 $http 方法的 URL