简体   繁体   中英

Function with arguements inside jQuery

Can someone please help why this is not working.

HTML Code:

<li><a href="#" onclick="adminDBDisplay(ownorg);" >OOrg</a></li>
<li><a href="#" onclick="adminDBDisplay(twoorg);" >Twoorg</a></li>

jQuery:

$(document).ready(function(){
    function adminDBDisplay(db){
        alert("Got into function" +db);
        // Planning to use jQuery Ajax here
    } 
});

When I look using Firebug, I get following error:

"ReferenceError: adminDBDisplay is not defined"

Can someone please help me why this is not working. There something wrong on how I am approaching this. Please let me know if there are better ways. Thanks for your help.

When defining a function with function name() {...} , if you are already inside a function, then it will only be defined in that function.

Function definitions should not be wrapped in a .ready() , since they don't run until they are called. Remove the .ready() wrapper and you should be good to go.

The following notation:

$(function() { ... });

itself is a function that binds function() {...} to document.ready . And running function adminDBDisplay(db){...} in document.ready only defines the function it at runtime, but doesn't actually call it. In order to call it, you would want adminDBDisplay('parameter');

To effectively implement it, you'll want to place it within the body of your page as follows:

<head>
<script src="yourversionofjquery.js"></script>
<script>
//Defining your function for calling later
function adminDBDisplay(db)
{
    alert("Got into function" +db);
    //Planning to use Jquery Ajax here
}
</script>
</head>
<body>
<script>
//Binding an anonymous function to document.ready
$(function () {
        //Do whatever you want after document.ready
    });
</script>
<div> rest of body</div>
</body>

Let me know if that makes sense/fixes your errors.

EDIT: also, put 'single quote' around 'ownorg', like "adminDBDisplay('ownorg');" otherwise it's looking for a variable called ownorg.

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