点击链接后询问确认

时间:2016-11-12 22:11:07

标签: jquery

我的HTML上有以下链接:

<a href="/posts/1/delete" class="delete">Delete</a>

我有点击事件:

$("a.delete").on("click", function (event) {
  // Delete post
}

但是,在删除帖子之前,我需要让用户确认。

所以我需要在HTML中添加以下内容:

<div class="message">Are you sure? Yes Button / No Button</div>

程序应该是这样的:

message.delay(400).slideDown(0.9)
// Ask question
message.slideUp(400, function () { $(this).remove(); });
// At the end the message DIV should be removed

我想将此作为可重用的插件。例如:

<a href="/posts/1/delete" class="delete confirm" data-question="Are you sure?">Delete</a>

我该怎么做?

1 个答案:

答案 0 :(得分:0)

(function ($) {
  $.fn.message = function (options) {
    $(this).each(function () {
      var $this = $(this);
      $this.on("click", function(e) {
        e.preventDefault();
        var cnfrm = $("<div class='cnfrm'>" + $this.attr("data-question") + "<button class='y'>Yes</button><button class='n'>No</button>");
        $this.after(cnfrm);

        cnfrm.find(".y").on("click", function() {
            $this.slideUp(400, function () { 
                $(this).remove();
                location.href = $this.attr("href");
            });
        });
      });
    });
    return this;
  };
})(jQuery);