Problems with e.preventDefault ()

I am having problems using preventDefault. The problem is that this piece of code is working fine (it prevents a click every time, and I get a warning):

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

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

But this is not so (nothig happens if the data is either "good" or not):

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

        });

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

Update

Thank you for your responses. How can I prevent Default () if I want it to act like in the second code snippet? I want e.preventDefault () to be executed only if the data! = "Ok".

+1
source share
4 answers

e.preventDefault() . , .

, , . - ( ).

$("#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, firebug.

+5

false, preventDefault stopPropogation

..

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

                }
            });
          return false
        });

, firebug -

0

hej user725912 isync , .

.

0

preventDefault()You can call the event handler function anywhere in the scope. It can be the first or last line, but cannot be inside another function inside it, especially not in the one that is called asynchronously.

Hope this helps.

0
source

Source: https://habr.com/ru/post/1691638/


All Articles