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

时间:2015-05-25 21:19:57

标签: javascript html function parameters 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
}

问题是,当创建每个新图像标记时,它实际上只是创建

<img src = "popo.jpg" onclick = "disappear(count)"/>

我希望它更像是

<img src = "popo.jpg" onclick = "disappear('1')"/>
<img src = "popo.jpg" onclick = "disappear('2')"/> //and so on...

3 个答案:

答案 0 :(得分:4)

在函数中添加count作为param,而不是字符串。

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
}

答案 1 :(得分:4)

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

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

Bind 会在调用时使count可用于此功能。

然后创建一个消失函数

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

答案 2 :(得分:2)

由于您使用的是setAttribute,因此您设置了event handler content attribute。相应的事件处理程序设置为internal raw uncompiled handler。该代码的范围将是

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

如果您的count变量在任何这些范围内都不可用,那么它将无法正常工作。即使它可用,因为你不断增加它,所使用的值将是修改后的值。

你不想要那个。相反,你可以:

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

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