在preventDefault()之后恢复默认行为

时间:2017-10-24 23:00:22

标签: javascript jquery

我写了一个小jQuery插件,旨在提出问题,“你确定吗?”点击链接或提交表单时。

它的使用方式如下:

<a href="link.php" class="confirm">Link</a>

或者像这样:

<form action="link.php" method="post">
    <button class="confirm">Submit</button>
</form>

我正在做的是使用preventDefault()来防止单击锚点或按钮时的默认行为。然后我显示一个确认对话框,用户必须单击“确定”或“取消”。

如果用户单击“取消”,则不会发生任何事情(按预期方式)。

但是,如果用户单击“确定”,我将再次触发单击事件,并使用第一次设置的标志,以防止第二次出现默认行为(我改为返回true)。除了它不起作用。在确认对话框中单击“确定”或“取消”不会执行任何操作。

插件如下:

(function($) {

    $.fn.fw_confirm = function(options) {

        // Flag to check for the first click event
        var paused = false;

        return this.on("click", function(e) {

            // The anchor or the button that was clicked
            var button = $(this);

            // If this is the second click event, the user must have confirmed so return true
            if (paused == true) {

                // Reset the flag
                paused = false;

                // This isn't working, or at least it's not submitting the form or proceeding to the URL of the hyperlink when I would expect it to
                return true;
            }

            // First time around prevent the default behavior
            e.preventDefault();
            e.stopImmediatePropagation();

            // Set the flag to true, ready for the second click event
            paused = true;

            if (confirm("Are you sure?")) {
                // The user is certain, so trigger the click event again
                return button.trigger("click");
            } else {
                // The user cancelled, reset the flag
                paused = false;
                return;
            }
        });
    }
})(jQuery);

0 个答案:

没有答案
相关问题