【问题标题】:Jquery to stop click event until function is completedJquery停止点击事件,直到功能完成
【发布时间】:2023-03-19 03:19:01
【问题描述】:

我有一个按钮,当它被点击时会触发:

var approved = false;

$('.confirm').on('click', function (e) {
    var type = $(this).attr("data-confirm");
    if (approved === false) {
        bootbox.confirm("Are you sure would like to " + type +"?", function (result) {
            if (result) {
                approved = true;
                $(this).trigger('click');
            }
        });
        e.preventDefault();
    }
});

它是一个带有 2 个按钮的模态确认框,取消和确认。 这里的目标是等待点击执行,直到用户点击确认框。 当代码运行时,它显示框并等待,如果用户单击取消,则关闭模态并且不触发单击,非常好,如果用户单击确认它关闭模态,则将批准分配给 true,但是单击新命令不会再次触发事件。

我怎样才能改变这个来执行这个。

如果批准为假,加载 bootbox.confirm 并暂停。如果(结果)将批准分配为 true,则用户点击确认其加载并继续点击。

有什么帮助吗?谢谢

【问题讨论】:

  • 已经尝试删除 e.preventDefault() 代码??
  • 我试图删除 e.preventDefault()。但现在它执行操作。它需要停止,以便用户可以选择要做什么。

标签: javascript jquery


【解决方案1】:

好的

我找到了解决方案,希望它可以帮助其他人。这是我的解决方案:

HTML

<button type="button" class="btn btn-primary mybutton" data-confirm="submit"> Submit</button>

JS

$('.mybutton').on('click', function (e) {
    var type = $(this).attr("data-confirm"),
    bootbox.confirm("Are you sure would like to " + type + "?", function (result) {
        if (result) {
           $('#Myform').submit();
        }
        else {
           e.eventPrevent();
        }
    });
});

基本上我所做的是将按钮类型从submit 更改为button。然后在单击按钮时,它会检查确认,如果用户单击是则提交表单,否则会阻止单击继续。

现在很好用。

【讨论】:

    【解决方案2】:

    我的问题是点击处理程序中的this 与点击的按钮不同

    var approved = false;
    
    $('.confirm').on('click', function (e) {
        var type = $(this).attr("data-confirm"),
            //use a closure variable since `this` inside the confirm callback is not the button
            $this = $(this);
        if (approved === false) {
            bootbox.confirm("Are you sure would like to " + type + "?", function (result) {
                if (result) {
                    approved = true;
                    $this.trigger('click');
                }
            });
            e.preventDefault();
        }
    });
    

    注意:这可能并不适用于所有情况。即,如果原始点击有一个可能不会触发的默认操作,如anchor 元素点击,或者如果注册了另一个点击处理程序可能仍会被触发。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-27
      • 2014-01-07
      • 1970-01-01
      • 1970-01-01
      • 2012-12-07
      • 2012-10-07
      • 2012-06-29
      • 1970-01-01
      相关资源
      最近更新 更多