i try to pass paramater to function. When i click the div it will alert the paramater that i pass
i have 2 file
- index.html
- script.js
here's what i try
Example 1
index.html
<div id="thediv" >
script.js
window.onload = initialize;
//bind event listener
function initialize(){
document.getElementById("thediv").onclick = myFunction(" something ");
}
//end of bind
//function
function myFunction(parameter) { alert( parameter ) };
//end of all function
- the trouble is the function its executed without click
Example 2
index.html
<div id="thediv" onclick="myfunction('something')" >
script.js
function myFunction(parameter) { alert( parameter ) };
- yap its done with this but the trouble if i have many element in index.html it will painful to read which element have which listener
- i want to separate my code into 3 section (similiar with example1)
- the view(html element)
- the element have which listener
- the function
what should i do? or can i do this? (i don't want to use another library)
-
Did you include the .js file? If you put an alert in the script.js, does it pop up?Jens Egholm– Jens Egholm2013年11月21日 10:14:21 +00:00Commented Nov 21, 2013 at 10:14
-
yes. i add it correctlyilike– ilike2013年11月21日 10:25:27 +00:00Commented Nov 21, 2013 at 10:25
3 Answers 3
Placing () (with any number of arguments in it) will call a function. The return value (undefined in this case) will then be assigned as the event handler.
If you want to assign a function, then you need to pass the function itself.
...onclick = myFunction;
If you want to give it arguments when it is called, then the easiest way is to create a new function and assign that.
...onclick = function () {
myFunction("arguments");
};
1 Comment
Your first solution logic is absolutely ok .. just need to assign a delegate ... what you are doing is calling the function .. So do something like this ...
//bind event listener
function initialize(){
document.getElementById("thediv").onclick = function () { myFunction(" something "); };
}
//end of bind
Comments
Instead of assign you invoke a function with myFunction();
Use it like this
//bind event listener
function initialize(){
document.getElementById("thediv").onclick = function(){
myFunction(" something ");
}
}