Javascript jQuery 单击事件防止默认

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11379794/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:39:52  来源:igfitidea点击:

jQuery Click Event PreventDefault

javascript

提问by Justin

If I have an atag:

如果我有一个a标签:

<a id="delete-event" href="/delete/1234">Delete</a>

And some javascript which prompts to confirm the delete:

还有一些提示确认删除的javascript:

 $("#delete-event").click(function(e) {
    e.preventDefault();

    bootbox.confirm("Are you sure you wish to delete this?", function(confirmed) {
        if(confirmed) {
            return true;
        }
    }); 
});

I thought doing e.preventDefault()would prevent the a hreffrom firing, but its not. When I click the a tag it simply goes to the url, without executing the javascript. How can I make this work?

我认为这样做e.preventDefault()会阻止a href发射,但事实并非如此。当我单击 a 标签时,它只是转到 url,而不执行 javascript。我怎样才能使这项工作?

Thanks.

谢谢。

回答by sachleen

This code works:

此代码有效:

You can't just do return trueand expect the link to fire after you've done e.preventDefault(). I had to replace your bootbox.confirm()with a JS confirm but it should still work.

你不能只做return true并期望链接在你完成后触发e.preventDefault()。我不得不bootbox.confirm()用 JS 确认替换你的,但它应该仍然有效。

$("#delete-event").click(function(e) {
    e.preventDefault();
    var a = confirm("yes?");
    if(a) window.location = $('#delete-event').attr('href');
});?

DEMO

演示

Try replacing your code block with the one I provided above. If that works, put your bootboxconfirmation back in and try again. That'll tell you where the error is.

尝试用我上面提供的代码块替换您的代码块。如果可行,请bootbox重新输入您的确认信息并重试。那会告诉你错误在哪里。

回答by SMathew

It's better to prevent it only when needed. For example, if the user selected "Cancel" from the confirm box, then prevent the default.

最好只在需要时防止它。例如,如果用户从确认框中选择了“取消”,则阻止默认设置。

$("#delete-event").click(function(e) {
    if (!confirm('Are you sure you wish to delete this?')) {
        e.preventDefault();
    } 
});?

Demo: http://jsfiddle.net/SCCDX/

演示:http: //jsfiddle.net/SCCDX/

Normally, when you need a confirm this is the best way to accomplish it, and it's event more useful for confirmations before submitting forms.

通常,当您需要确认时,这是完成它的最佳方式,并且在提交表单之前进行确认更有用。

I am not sure if bootbox replicates the behavior of browsers when you ask for confirmation. So it may not work in this scenario. If that is the case a better approach is to set a flag somewhere.

当您要求确认时,我不确定 bootbox 是否会复制浏览器的行为。所以在这种情况下它可能不起作用。如果是这种情况,更好的方法是在某处设置一个标志。

$("#delete-event").click(function(e) {
    if (!$(this).data('confirmed')) {
       e.preventDefault()
    } else {
       bootbox.confirm("Are you sure you wish to delete this?", function(confirmed) {
          if(confirmed) {
              $(this).data('confirmed', 1).click();           
          }
       });        
    }
});?

// Disclaimer: This code is untested. clicking on the link may cause data loss. lol 

Somehow, I don't like the window.location method, cause it may cause any other events attached to this element to fail.

不知何故,我不喜欢 window.location 方法,因为它可能导致附加到此元素的任何其他事件失败。

回答by lonecat

I met this problem too.

我也遇到了这个问题。

You can use window.location make browser visit new page, but current page is not recorded in the browser history (at least with google chrome).

您可以使用 window.location 使浏览器访问新页面,但当前页面不会记录在浏览器历史记录中(至少使用谷歌浏览器)。

So I agree with SMathew that the new event should be triggered. But due to some security reason, the click event on anchors triggered by jQuery do not make browser visit new page. Finally I found the following code works.

所以我同意 SMathew 的观点,即应该触发新事件。但是由于一些安全原因,jQuery 触发的锚点上的点击事件不会使浏览器访问新页面。最后我发现以下代码有效。

$("a.confirm").on('click', function(e) {
    if (!$(this).data('confirmed')) {
        e.preventDefault();
        var a = this;
        bootbox.confirm("Are you sure?", "No", "Yes", function(result) {
            if(result) {
                $(a).data('confirmed', 1);
                if (document.createEvent) {
                    var evObj = document.createEvent('MouseEvents');
                    evObj.initEvent('click', true, true);
                    a.dispatchEvent(evObj);
                }
                else if (document.createEventObject) {
                    a.fireEvent('onclick');
                }
            }
        });
    }
});

I just test above code in google chrome, and I found fire event code from https://getsatisfaction.com/issuu/topics/opening_the_issuu_smartlook_viewer_with_my_flash_website?utm_content=topic_link&utm_medium=email&utm_source=reply_notification

我只是在谷歌浏览器中测试了上面的代码,我发现了来自https://getsatisfaction.com/issuu/topics/opening_the_issuu_smartlook_viewer_with_my_flash_website?utm_content=topic_link&utm_medium=email&utm_source=reply_notification 的火灾事件代码

MORE

更多的

I found this post https://stackoverflow.com/a/18132076/1194307, and jQuery.simulatecan be used to solve this problem. My final code looks like:

我找到了这篇文章https://stackoverflow.com/a/18132076/1194307jQuery.simulate可以用来解决这个问题。我的最终代码如下所示:

$("[data-toggle=confirm]").on('click', function(e) {
    var a = $(this);
    if (!a.data('confirmed')) {
        e.preventDefault();

        var question = a.data('question');
        if (!question) question = 'Are you sure?';

        var yes = a.data('yes');
        if (!yes) yes = 'Yes';

        var no = a.data('no');
        if (!no) no = 'No';

        bootbox.confirm(question, no, yes, function(result) {
            if(result) {
                a.data('confirmed', 1).simulate('click');
            }
        });
    }
});

It works on anchors and form buttons.

它适用于锚点和表单按钮。

回答by Navdeep

Try this code:

试试这个代码:

$(".SelectedPassengers").each(function () {
            debugger;

        if ($(this).text() == "") {
            debugger;
            var id = this.id.split('-');
            alert("Please Select Passenger " + id[1]);
            var h = "" + this.id;
          // $(this).preventDefault();
           //$('#' + h).focus();
           //this.preventDefault();
           stopEvent = "enter";
        }

    });
    if (stopEvent != "") {
        stopEvent = "";
        event.preventDefault();
        return false;
    }

回答by Dean Brundage

You need to return false;for anchor tags.

你需要return false;锚标签。

See this jsFiddle.

看到这个 jsFiddle