JavaScript 帮助要求从 onclick 获取动态值
我正在创建 20 动态 div ,在页面加载时将 onclick 事件附加到每个 div 以提醒其 id,但问题是单击任何 div 时仅提醒最后一个 div id,请帮助。
例如,单击第一个 div 会提醒最后一个 div id。
所需的结果是 div 上的 onclick 应该提醒其自己的 id。
完整代码如下。
提前致谢。
<html>
<head>
<script>
function __createElement(tag, cls, id, name)
{
var ele;
ele = document.createElement(tag);
if(cls!="" && cls!=undefined)
ele.className = cls;
if(id != "" && id!=undefined)
ele.id = id;
if(name!= "" && name!=undefined)
ele.name = name;
return ele;
}
function test()
{
for(var i = 0;i<20;i++)
{
var div = __createElement("div" ,"test" ,i+"test");
document.getElementById("cont").appendChild(div);
div.innerHTML = "Content"+i;
div.onclick = function ()
{
alert(i+"test");
}
}
}
setTimeout("test()",1000);
</script>
</head>
<body>
<div id=cont >
</div>
</body>
</html>
I am creatind 20 dynamic div , on page load attaching onclick event to each div to alert its id but problem is on clicking any div only last div id is alerted plz help.
For example on clicking on fist div is alerting last div id.
Required result is onclick on a div should alert its own id.
Full code is given bellow.
Thanks in advance.
<html>
<head>
<script>
function __createElement(tag, cls, id, name)
{
var ele;
ele = document.createElement(tag);
if(cls!="" && cls!=undefined)
ele.className = cls;
if(id != "" && id!=undefined)
ele.id = id;
if(name!= "" && name!=undefined)
ele.name = name;
return ele;
}
function test()
{
for(var i = 0;i<20;i++)
{
var div = __createElement("div" ,"test" ,i+"test");
document.getElementById("cont").appendChild(div);
div.innerHTML = "Content"+i;
div.onclick = function ()
{
alert(i+"test");
}
}
}
setTimeout("test()",1000);
</script>
</head>
<body>
<div id=cont >
</div>
</body>
</html>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一个变量闭包问题,请使用它:
this a variable closure issue use this instead:
我曾经遇到过这个问题。请记住:在
test()
函数的整个范围内,i
的值现在为 20。但是,每个 div 的innerHTML
值现在已按您的预期设置。因此,请改用innerHTML
值引用。I came across this problem once. Just remember: the value of
i
is now 20 across the entire scope of thetest()
function. But, theinnerHTML
value of each div is now set as you'd expect. So use thatinnerHTML
value reference instead.