qu******@yahoo.com wrote:
Hi, here is my code:
<html>
<head>
<script type="text/javascript">
function setImage(num)
You seem to expect to pass a value to the function, but your code below
doesn't do that. I'll guess that you are trying to pass 'i' from init's
for loop.
{
alert(num);
}
function init()
{
for (var i = 0; i < 5; i++){
var button = document.createElement("input");
button.type = "button";
button.value = "Image ";
button.onclick = setImage(button);
That will assign the result of setImage(button) to the value of the
button's onclick attribute. What you need to do is assign a reference
to the function itself:
button.onclick = setImage;
But you want to pass a value, so the next thing that you might try is:
button.onclick = function(){ setImage(i); }
Which 'works', but it creates a closure back to the init's local i. All
the buttons will alert '5', which is the value of i when the function
finished, not its value when each onclick handler was set.
There are a couple of ways to break the closure, one is to use the
Function object as a constructor, but that is not liked as it is
considered only marginally better than using eval. You can either
create a separate function to add the onclick:
function addOnclick(obj, func, val){
obj.onclick = function(){func(val)};
}
and call it like:
addOnclick(input, setImage, i);
or you can use a function expression:
input.onclick = (function(i){
return function(){ setImage(i);}
})(i);
which is somewhat more convoluted, but probably neater overall.
[...]
--
Rob