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

标签 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...

最佳答案

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

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/

相关文章:

php - 结合托管在 Web 服务器上的 PHP 和 jQuery 来使用 POST 函数提交表单?

r - 我在if条件下缺少值错误

javascript - 请求超时

javascript - 指令相互干扰

javascript - 指定秒的 JW Player 事件

html - style 标签中的 import filename.css 与 link 标签的导入率如何与 css 文件相关

JavaScript 动画短笔画和长笔画

javascript - scrapy没有检测到html元素,但它在源页面上可见

html - 为嵌套列表重置 CSS 计数器,格式为 1.1、1.2、

bash - 为什么要为私有(private)函数加双下划线 (__)?为什么 (_) 用于 bash 完成函数?