我正在try 使用jQueryUI对话框来替换丑陋的javascript:alert()框.

<ul>
    <li>ITEM <a href="url/to/remove"> <span>$itemId</span>
    <li>ITEM <a href="url/to/remove"><span>$itemId</span>
    <li>ITEM <a href="url/to/remove"><span>$itemId</span>
</ul>

<div id="confirmDialog">Are you sure?</div>

在JQ Part中,在Document Ready上,我首先将div设置为带有必要按钮的模式对话框,并在删除之前将那些要触发的"a"设置为确认,例如:

$("ul li a").click(function() {
  // Show the dialog    
  return false; // to prevent the browser actually following the links!
}

好吧,问题来了.在初始化期间,对话框将不知道谁(项)将启动它,也不知道项id(!).我如何设置这些确认按钮的行为,以便在用户仍然 Select "是"时,它将按照链接删除它?

推荐答案

我只是不得不解决同样的问题.实现这一点的关键是,对于要使用确认功能的链接,必须在click事件处理程序中对dialog进行部分初始化(如果要将其用于多个链接).这是因为必须将链接的目标URL注入到用于确认按钮单击的事件处理程序中.我使用了一个CSS类来指示哪些链接应该具有确认行为.

Here's my solution, abstracted away to be suitable for an example.

<div id="dialog" title="Confirmation Required">
  Are you sure about this?
</div>

<script type="text/javascript">
  $(document).ready(function() {
    $("#dialog").dialog({
      autoOpen: false,
      modal: true
    });
  });

  $(".confirmLink").click(function(e) {
    e.preventDefault();
    var targetUrl = $(this).attr("href");

    $("#dialog").dialog({
      buttons : {
        "Confirm" : function() {
          window.location.href = targetUrl;
        },
        "Cancel" : function() {
          $(this).dialog("close");
        }
      }
    });

    $("#dialog").dialog("open");
  });
</script>

<a class="confirmLink" href="http://someLinkWhichRequiresConfirmation.com">Click here</a>
<a class="confirmLink" href="http://anotherSensitiveLink">Or, you could click here</a>

I believe that this would work for you, if you can generate your links with the CSS class (confirmLink, in my example).

Here is a jsfiddle with the code in it.

In the interest of full disclosure, I'll note that I spent a few minutes on this particular problem and I provided a similar answer to this question, which was also without an accepted answer at the time.

Jquery相关问答推荐

JQuery AJAX 成功事件未触发

使用 JQuery 在 span 标签中用逗号分隔页面上的文本

为什么我的 toFixed() 函数不起作用?

如何使用 jQuery Select 所有复选框?

jQuery.parseJSON 单引号与双引号

可以在不使用for=id的情况下将标签与复选框相关联吗?

在 contenteditable div 中的插入符号处插入 html

jQuery UI 对话框 - 关闭后不打开

删除所有子元素的 CLASS

如何使用 jQuery 进行带命名空间的 XML 解析

为什么不推荐$().ready(handler)?

jQuery - 多个 :not Select 器

禁用 jquery Select 的下拉菜单

jQuery:如何创建一个简单的叠加层?

父母的jQuery父母

将多个 JavaScript 文件合并为一个 JS 文件

如何在一个元素上拥有多个数据绑定属性?

jQuery DataTables:控制表格宽度

如何获取第一个元素而不是在 jQuery 中使用 [0]?

获取对象属性中的最小值/最大值的快速方法