Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add parameters onto function in setAttribute() method in javascript

In javascript, I was creating new image tags and I was adding attributes to them with the setAttribute() method but I found that if I add an onclick event and add a function, I can't set in a parameter for it as seen below

count = 0; //Will be the number that will go into parameter for function
function start() {
imageTag = document.createElement("IMG"); //Creates image tag
imageTag.setAttribute("src", "popo.jpg"); //sets the image tags source
count++; //as the start function keeps getting called, count will increase by 1 and the parameter for each function in each individual image tag will increase by one
imageTag.setAttribute("onclick", "disappear(count)"); //this will add the onclick attribute with the function disappear() and the parameter inside which will be a number that will increase as the start function is called again and the image tag is called again *ERROR*
document.body.appendChild(imageTag); //appends the image tag created
}

The problem is, when each new image tag is created, it literally just creates

<img src = "popo.jpg" onclick = "disappear(count)"/>

I wanted it to be more like

<img src = "popo.jpg" onclick = "disappear('1')"/>
<img src = "popo.jpg" onclick = "disappear('2')"/> //and so on...
like image 392
user3450498 Avatar asked Nov 30 '22 10:11

user3450498


1 Answers

add count in function as param, not as string.

count = 0; //Will be the number that will go into parameter for function
function start() {
    imageTag = document.createElement("IMG"); //Creates image tag
    imageTag.setAttribute("src", "popo.jpg"); //sets the image tags source
    count++; //as the start function keeps getting called, count will increase by 1 and the parameter for each function in each individual image tag will increase by one
    imageTag.setAttribute("onclick", "disappear("+count+")"); //this will add the onclick attribute with the function disappear() and the parameter inside which will be a number that will increase as the start function is called again and the image tag is called again *ERROR*
    document.body.appendChild(imageTag); //appends the image tag created
}
like image 168
user3227295 Avatar answered Dec 09 '22 20:12

user3227295