简体   繁体   中英

function parameter is not passed as expected

I'm appending input buttons to a div and adding an onclick event to each button in the following way:

function initializeImages(imagesStr) 
{   
imagesArr = imagesStr.split(";");

imagesDiv = document.getElementById("buttons");

for (i=0 ; i<imagesArr.length ; i++)
{
    //Create button
    button = document.createElement('input');
    button.type = "button";
    button.className = "image_button";
    button.value = i+1;
    button.onclick = function(){showImage(imagesArr[i]);};

    //Append Button
    imagesDiv.appendChild(button);
}   
} 

but the parameter imagesArr[i] is passed as undefined.

I'v tried saving it to a variable before passing it:

var image = imagesArr[i];
button.onclick = function(){showImage(image);};

but that way the function receives a reference to that static variable and always gets the last value.

any suggestions?

It's undefined because it isn't until the click callbacks are invoked that i is evaluated. By then i has gone beyond the length of your images array.

Try

button.onclick = (function (i) {
    return function () {
        showImage(imagesArr[i]);
    };
}(i));

what if you change:

button.onclick = function(){showImage(imagesArr[i]);};

to this:

button.onclick = showImage;

...

function showImage(el) {
    var index = parseInt(el.target.getAttribute('value'), 10);
    var image = imagesArr[index-1]

do you serve this?

<html>
<head>
<script>
var imgs= ['btn1','btn2','btn3'];
function AddImages(arr,dest){
    for(i in arr){
        document.getElementById(dest).innerHTML += '<input type="button" class="'+arr[i]+'" value="'+(parseInt(i)+1)+'" onclick="alert(\''+arr[i]+'\');"/>';
    }
}
</script>
<style>
.btn1 {
background-color:red;
}
.btn2 {
    background-color:green;
}
.btn3 {
    background-color:blue;
}
</style>
<body>
<div id="button"></div>
<a href="#test" onclick="AddImages(imgs,'button');">Add Images</a>
</body>
</html>

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