简体   繁体   中英

Function not defined - jQuery/Javascript

Another hapless noob... Okay, so I've looked everywhere to try and find out how to make this jQuery/JavaScript function, I hope it's just a mistake in my syntax, but here's my code:

<script type="text/javascript">

$(function()
{
        function loadNext(choice) {
            $("#thequestion").load("question.php", { ans: choice, id: "<?php echo $row['id']; ?>", nextId: "<?php echo $nextQuestionId; ?>" } );

            $("#graph").load("graph.php", { id:"<?php echo $row['id']; ?>", nextId: "<?php echo $nextQuestionId; ?>" } );
            alert("loadNext activated");
        }

});
</script>

I then call the loadNext(choice) function using an onclick event like so: onclick="loadNext(YorN);" .

Following this I get a 'loadNext is not defined' error.

Amongst the answers that I would accept are: "YU NO LEARN!" and "You are silly."

Here is a similar problem.

Thanks.

The loadNext function you just defined is local to the scope of your anonymous function. If you want to access it globally, then define it globally (outside of your onready handler).

The outer "$(function().." you have on your first line limits your scope - the loadNext function is only available within this block and will be undefined outside of it.

The easy way to get around this is to just define the "loadnext" function outside the $(function()..) block but this is wrong for two reasons:

  1. This makes the function global across your entire application, and polluting the global namespace is a no-no.
  2. Inline javascript like "onclick" is bad in general - this blurs the line between presentation and logic and makes debugging a pain.

To get around this, use the jquery bind events to attach your event handlers; ie,

$("#myfancybutton", click(function(){ loadNext(choice) }); within your $(function()..) bloc

because you have a function inside a function

 (function()
{
        function loadNext(choice) {
            this is bad
        }

function loadNext(choice) {
            this is good
        }

onclick="loadNext()"

no probs

为什么不将loadNext函数放在$(function(){})之外呢?

Because loadNext is not in global scope. You can define it in global scope, or even better solution is to use .click() to bind your click event.

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