Hi I am learning JQuery and I have written a small function where I am attaching a function with a button’s click event.
this is the head element of the HTML
<script type="text/javascript">
$(pageLoaded);
function pageLoaded()
{
$("#Button1").bind("click",
{ key1: "value1", key2: "value2" },
function buttonClick(event)
{
$("#displayArea").text(event.data.key1);
}
);
}
</script>
This is the body of the HTML
<input id="Button1" type="button" value="button" />
<div id = "displayArea" style="border:2px solid black; width:300px; height:200px">
This code works fine. But when I try to write the buttonClick function outside the anonymus method, it does not work anymore.
I tried to call it this way:
$("#Button1").bind("click",
{ key1: "value1", key2: "value2" },
buttonClick(event));
function buttonClick(var event)
{
$("#displayArea").text(event.data.key1);
}
This is not working. Am I doing some mistake while passing the Event as parameter? what is the correct way to do it without using anonymous methods?
You need to pass a
function referenceas the click handler, but what you are doing hereis calling
buttonClick(event)immediately and whichreturn undefinedand sets that as theclick handler. You have to pass a function reference likebuttonClickand you will get event param automatically (jQuery will send that when calling the handler).Full Code:
Demo: http://jsfiddle.net/joycse06/cjc9r/
Update (Based On @Tadeck’s comment):
Your code will work fine if you use
function expressionlike thisAnd you have to place this above its
first use. In this case beforeBecause
function expressionsare nothoistedat the top of current scope likefunction declaration. So you can use themonly aftertheexpressionhas beeninterpretedbyJS interpreter.