e.preventDefault()问题 [英] Problems with e.preventDefault()

查看:154
本文介绍了e.preventDefault()问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用preventDefault时遇到问题.问题是这段代码可以正常工作(它每次都会阻止单击,并且我得到警报):

I have problems using preventDefault. The problem is that this piece of code works fine (it prevents the click everytime and I get the alert):

$("#vnesi").click(function (e) {
            $.post("/VnosPrijavnica/PreveriVnose", $("#kriteriji").serialize(), function (data) {
                if (data != "ok")
                    alert(data);

            });
            e.preventDefault();
        });

但这不会(如果数据确定"或没有,则不会发生):

But this doesn't (nothig happens, if data is either "ok" or not):

        $("#vnesi").click(function (e) {
            $.post("/VnosPrijavnica/PreveriVnose", $("#kriteriji").serialize(), function (data) {
                if (data != "ok"){
                    alert(data);
                    e.preventDefault();
                }
            });

        });

还有一个问题.在Firefox 4(或任何其他浏览器,但我更喜欢Firefox 4)中调试JavaScript的最佳方法是什么?

And also one more question. What is the best way to debug javascript in Firefox 4 (or any other browser but I prefer Firefox 4)?

更新

感谢您的回答.如果我想让它像第二段代码一样工作,该如何防止Default()?我希望e.preventDefault()仅在数据!="ok"时执行.

Thanks for your answers. How can I preventDefault() if I want it to act like in the second piece of code? I want e.preventDefault() to execute only if the data != "ok".

推荐答案

您在异步回调中调用e.preventDefault().在您阻止该事件之前,该事件处理程序将已经完成.

Your calling e.preventDefault() in an asynchronous callback. The event handler will have completed before you prevented the event.

基本上,您无法在回调中更改事件,因为事件已完成.您需要以不同的方式(即在回调之外)进行处理.

Basically you cannot change the event in the callback because the event has completed. You need to handle this differently (i.e. outside the callback).

$("#vnesi").click(function(e) {
    $.post("/VnosPrijavnica/PreveriVnose", $("#kriteriji").serialize(), function(data) {
        if (data != "ok") {
            alert(data);
        } else {
             // ajax post failed 
             // trigger the action of the event again. (form.submit ??)
        }
    });
    // prevent the default always
    e.preventDefault();
});

用于在firefox中进行调试.请使用内置构建工具(Ctrl + Shift + J)或安装firebug .然后使用F12打开萤火虫.

For debugging in firefox. Either use the in build tools (Ctrl+Shift+J) or install firebug. Then use F12 to open firebug.

这篇关于e.preventDefault()问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆