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

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

本文关键字:方法 函数 参数 添加 javascript setAttribute      更新时间:2023-09-26

在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作为参数,而不是作为字符串。

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
}

不添加click event作为属性,使用addEventListener

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

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

然后创建一个消失函数

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

由于您使用setAttribute,因此您正在设置事件处理程序内容属性。相应的事件处理程序设置为内部原始未编译处理程序。该代码的作用域为

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

如果你的count变量在这些范围中不可用,它将无法工作。即使它是可用的,由于您不断增加它,使用的值将是修改后的值。

但是你不希望那样。相反,您可以:

  • 在未编译的处理程序中写入变量:

    imageTag.setAttribute("onclick", "disappear(" + count + ")");
    
  • 使用事件处理程序IDL属性,例如

    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}')`);