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...
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With