use*_*498 4 html javascript parameters function setattribute
在 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
}
Run Code Online (Sandbox Code Playgroud)
问题是,当每个新的图像标签被创建时,它实际上只是创建
<img src = "popo.jpg" onclick = "disappear(count)"/>
Run Code Online (Sandbox Code Playgroud)
我想让它更像
<img src = "popo.jpg" onclick = "disappear('1')"/>
<img src = "popo.jpg" onclick = "disappear('2')"/> //and so on...
Run Code Online (Sandbox Code Playgroud)
小智 7
在函数中添加计数作为参数,而不是字符串。
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
}
Run Code Online (Sandbox Code Playgroud)
而不是添加点击事件作为属性添加它使用addEventListener
imageTag.addEventListener("click", disappear.bind(null, count));
Run Code Online (Sandbox Code Playgroud)
Bind将count在调用时对函数可用。
然后创建一个消失函数
function disappear(ID){
alert(ID); // This should give the count.
}
Run Code Online (Sandbox Code Playgroud)
由于您使用setAttribute,您正在设置事件处理程序内容属性。相应的事件处理程序设置为内部原始未编译处理程序。该代码的范围将是
如果您的count变量在这些范围中的任何一个范围内都不可用,则它将不起作用。即使它可用,由于您不断增加它,使用的值将是修改后的值。
但是你不想那样。相反,您可以:
在未编译的处理程序中写入变量:
imageTag.setAttribute("onclick", "disappear(" + count + ")");
Run Code Online (Sandbox Code Playgroud)使用事件处理程序 IDL 属性,例如
var localCount = count; // Using a local copy in case `count` is modified
imageTag.onclick = function() {
disappear(localCount);
};
Run Code Online (Sandbox Code Playgroud)