JQuery :添加具有绑定/打开和触发器函数的确认处理程序

JQuery : Add a confirm handler with bind/on and trigger functions

本文关键字:函数 触发器 确认 程序 处理 添加 绑定 JQuery      更新时间:2023-09-26

>我正在尝试在单击事件上向许多链接、按钮或输入添加一个确认框。

我不能使用 location.href、submit() 或其他特定功能,因为:

  • 例如,location.href 不适用于提交按钮,
  • 例如,location.href 不会触发其他绑定处理程序。

所以我需要使用的是 trigger() 函数,它在理论上执行所有处理程序和本机操作。"困难"的部分是执行所有处理程序,除了弹出确认框的处理程序。

这是我的代码:

$('a, button, input[type="submit"]').each(function() {
    var oButton = $(this);
    oButton.on('click.pending', function(oEvent) {
        console.log('click !');
        oEvent.preventDefault();
        var oDialog = $('<div class="dialog-example">[Question] ?</div>').dialog({
            buttons: {
                Cancel: function() {
                    console.log('cancelled !');
                    // Nothing to do
                    oDialog.dialog('close');
                },
                Ok: function() {
                    console.log('confirmed !');
                    // Trigger the rest of the handlers AND the native action, BUT not this one, so this dialog is not used
                    // Problem : nothing happens here
                    oButton.trigger('click.confirmed');
                    oDialog.dialog('close');
                }
            }
        });
    });
});

提前感谢 ! ;)

你应该尝试:

oButton.off('click.pending').trigger('click').get(0).click();

演示