views:

65

answers:

4

First off, here's my code:

var variable1 = 10;
  function f1 (){
  alert(variable1);
  }
//When button is pressed, call function
$("#button").click(f1);

Why can I not access variable1 inside the function? Many thanks and a Happy Christmas.

Modified question

$(document).ready(function() {

var how_many_words = 3;
alert(how_many_words);  //This happens

$("input").keypress(check_word);

function check_word(){
alert('hello');         //This happens
alert(how_many_words);  //This doesn't
    }

    });
A: 

Try:

 var variable1 = 10;
 var f1 = function(){
     alert(variable1);
 }
 //When button is pressed, call function
 $("#button").click(f1);

Too hungover to explain. Sorry!

Commenters are correct, ignore the above. Just mocked up your issue. Your code works fine for me:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml"&gt;
 <head>
  <title>
   test
  </title>

  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"&gt;&lt;/script&gt;
 </head>
 <body>
  <div id="button">hello</div>
  <script type="text/javascript">
   //<![CDATA[
    var variable1 = 10;
    function f1 (){
     alert(variable1);
    }
    //When button is pressed, call function
    $("#button").click(f1);

   //]]>
  </script>
 </body>
</html>
spender
function x() { ... } is syntactic sugar for var x = function () { ... };.
AKX
this will also fail
streetparade
My hangover bigger than my programming powers...
spender
I must have simplified my problem incorrectly. I'll come back with the correct question as soon as possible.
Patrick Beardmore
@AKX, actually, they're both VERY different - http://yura.thinkweb2.com/named-function-expressions/
J-P
@J-P: Thanks for the clarification! I must've mixed Lua and JS up. In Lua, I'm fairly sure function x() end is sugary...
AKX
A: 

I'm quite sure that you can access variable1 from inside of f1. What happens when you try?

One thing I notice is that you're calling alert with an int argument. I'm not sure if that works. Try

alert(variable1.toString());

instead.

EDIT: OK, never mind that bit; alert(int) certainly does work.

Dan Breslau
+1  A: 

Your problem is actually not that you can't access the variable, but that the #button element is not in the DOM yet when your binding code is called. Wrap your initialization code in the jQuery DOM ready idiom:

$(document).ready(function() {
    $("#button").click(f1);
});
AKX
I think you've nailed it.
Dan Breslau
This is only a snippet of much more code so that isn't the problem.
Patrick Beardmore
+1  A: 

Here's the definitive answer to what my problem was, courtesy of this website. I foolishly named one of my variables the same as an id and a function. Insanity! I apologise for wasting people's boxing days. Thanks for all your help.

Patrick Beardmore