如何在 javascript 中的 setAttribute() 方法中将参数添加到函数中

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

在 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
}

不要将点击事件添加为属性,而是使用 addEventListener

添加它
imageTag.addEventListener("click", disappear.bind(null, count));

Bind 将使 count 在调用时可用于函数。

然后创建一个消失函数

function disappear(ID){
  alert(ID); // This should give the count.
}

由于您使用 setAttribute,因此您设置的是 event handler content attribute. The corresponding event handler is set to an internal raw uncompiled handler。该代码的范围将是

  • 全局对象
  • 文档
  • 表单所有者(如果有)
  • 元素(如果有)

如果您的 count 变量在任何这些范围内都不可用,它将不起作用。而且即使可用,因为你一直增加它,所以使用的值将是修改后的值。

但你不想这样。相反,您可以:

  • 在未编译的handler中写入变量:

    imageTag.setAttribute("onclick", "disappear(" + count + ")");
    
  • 使用event handler IDL attributes,例如

    var localCount = count; // Using a local copy in case `count` is modified
    imageTag.onclick = function() {
        disappear(localCount);
    };
    

在参数函数中将""更改为''

之前::

imageTag.setAttribute("onclick", "disappear(" + count + ")");

之后::

imageTag.setAttribute("onclick", "disappear('" + count + "')");

最佳实践::

imageTag.setAttribute("onclick", `disappear('${count}')`);