简体   繁体   中英

function not working on click? (jquery/javascript)

This is the most frustrating error I have probably ever had while coding. I'm trying to click a button and have it pop up "hello" in an alert box. If I remove the document ready it works. If I remove the function and just have the alert box in the document.ready, it also works but obviously without a click. However, that JS doesn't work all together and I have no idea why.

HTML

<button id="signup-box-button" type="button" onclick="signupSubmit()">sign up</button>

JS

$(document).ready(function(){

    function signupSubmit(){
        alert("hello");
    }

});

When you put a function or variable inside a function its scope is limited to that function, this means that it will be visible only when inside that function.

To solve this, just move the function that is used outside of "ready function" to be visible outside.

$(document).ready(function(){
    // code here
});

function signupSubmit(){
    alert("hello");
}

Or, better yet. Leave Javascript code to Javascript file only, and let the HTML with HTML only.

HTML

<button id="signup-box-button" type="button">sign up</button>

Javascript

$(document).ready(function(){
    $('#signup-box-button').click(function(){
        alert("hello");
    }
});

This is because of scoping in javaScript as explained by Skarllot

Please refer to know how this keyword works with inline event handlers.

You can use the below code snippet

$(document).ready(function(){

     this.signupSubmit = function(){
        alert("hello");
    }

});

Refer JSFIDDLE

By adding this keyword the function will be registered in global scope. And the above solution may pollute the global namespace.

To better understand the above functionality:

Inline event handlers are evaluated in global scope. In your first example, signupSubmit is not defined in global scope, it is defined inside the function you pass to $(document).ready . Hence the inline event handler cannot find the function.

Here is a simplified example:

function ready() {
    function signupSubmit() { }
}

ready();
signupSubmit(); // ReferenceError because signupSubmit is not defined in this scope

Note that there is no reason to put function definitions inside a $(document).ready callback, except for explicitly not putting them in global scope by using this keyword as mentioned in my first example.

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