在 javascript 中,我正在创建新的图像标签并使用 setAttribute() 方法向它们添加属性,但我发现如果我添加一个 onclick 事件并添加一个函数,我无法为其设置参数如下所示
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
}
问题是,当创建每个新图像标签时,它实际上只是创建
<img src = "popo.jpg" onclick = "disappear(count)"/>
我希望它更像
<img src = "popo.jpg" onclick = "disappear('1')"/>
<img src = "popo.jpg" onclick = "disappear('2')"/> //and so on...
最佳答案
在函数中添加计数作为参数,而不是字符串。
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
}
关于javascript - 如何在javascript中的setAttribute()方法中将参数添加到函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30446152/