简体   繁体   中英

Prevent Function Execution in Javascript and JQuery

I have such a code block and when code finds an error attribute which is set to error, then it should prevent further execution, how can I prevent it from execution :

$(document).ready(function() {
    $("#SendMessage").click(function(e) {
        var elements = $("#contact-area input:text[error=error]").get();
        for (var i = 0; i < elements.length; i++) {
            if ($(elements[0]).attr("error") == "error") {
                alert("error found");
                // Stop execution of whole function
            }
        }
        $("#loaderImage").show();
        $("#statusMessage").text("Sending, Please wait...");
        window.setTimeout(function() { PageMethods.SendMessage(new Message().fullContent(), onSuccess(), onFailed()) }, "4000");
    });
})

And How can I do that with both JQuery and Javascript, maybe there is a pre-defined function to do that easily in JQuery.

$(document).ready(function() {
    var flag = false;
    $("#SendMessage").click(function(e) {
        var elements = $("#contact-area input:text[error=error]").get();
        for (var i = 0; i < elements.length; i++) {
            if ($(elements[0]).attr("error") == "error") {
                alert("error found");
                // Stop execution of whole function
                flag = true;
                break;
            }
        }
        if (!flag){
          $("#loaderImage").show();
          $("#statusMessage").text("Sending, Please wait...");
        window.setTimeout(function() { PageMethods.SendMessage(new Message().fullContent(), onSuccess(), onFailed()) }, "4000");
        }
    });
})

Would that accomplish what you need?

just return; when the error is found

$(document).ready(function() {
    $("#SendMessage").click(function(e) {
        var elements = $("#contact-area input:text[error=error]").get();
        for (var i = 0; i < elements.length; i++) {
            if ($(elements[0]).attr("error") == "error") {
                alert("error found");
                return;
            }
        }
        $("#loaderImage").show();
        $("#statusMessage").text("Sending, Please wait...");
        window.setTimeout(function() { PageMethods.SendMessage(new Message().fullContent(), onSuccess(), onFailed()) }, "4000");
    });
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM