我在表单中添加了 3 个 div 元素,并为每个元素动态添加了事件处理程序。它应该弹出一条消息,显示该 div 的 id。但是,无论我单击哪个框,它都会弹出最后一个 div 的 id,即 10175。
任何意见都将受到赞赏。
<html>
<head>
<style type="text/css">
.empty
{
background-color: green;
}
.safebox
{
margin-left: auto;
margin-right: 20px;
margin-top: 20px;
text-align: center;
float: left;
width: 60px;
height: auto;
}
</style>
<script type="text/javascript">
function ClickMe(elem){
alert(elem.id);
};
window.onload=function(){
var tempdiv = document.createElement('div');
var text = document.createTextNode('0173');
tempdiv.className='safebox empty';
tempdiv.appendChild(text);
tempdiv.setAttribute('id','10173');
tempdiv.appendChild(text);
document.getElementById('pagewarpper').appendChild(tempdiv);
var currentdiv = document.getElementById('10173');
if (currentdiv.addEventListener){
currentdiv.addEventListener('click', function(){ClickMe(currentdiv);}, false);
}
else {
currentdiv.attachEvent('onclick', function(){ClickMe(currentdiv);});
}
var tempdiv = document.createElement('div');
var text = document.createTextNode('0174');
tempdiv.className='safebox empty';
tempdiv.appendChild(text);
tempdiv.setAttribute('id','10174');
tempdiv.appendChild(text);
document.getElementById('pagewarpper').appendChild(tempdiv);
var currentdiv = document.getElementById('10174');
if (currentdiv.addEventListener){
currentdiv.addEventListener('click', function(){ClickMe(currentdiv);}, false);
}
else {
currentdiv.attachEvent('onclick', function(){ClickMe(currentdiv);});
}
var tempdiv = document.createElement('div');
var text = document.createTextNode('0175');
tempdiv.className='safebox empty';
tempdiv.appendChild(text);
tempdiv.setAttribute('id','10175');
tempdiv.appendChild(text);
document.getElementById('pagewarpper').appendChild(tempdiv);
var currentdiv = document.getElementById('10175');
if (currentdiv.addEventListener){
currentdiv.addEventListener('click', function(){ClickMe(currentdiv);}, false);
}
else {
currentdiv.attachEvent('onclick', function(){ClickMe(currentdiv);});
}
}
</script>
</header>
<body>
<form>
<div id="pagewarpper">
</div>
</form>
</body>
最佳答案
尝试
ClickMe(this);
使用 currentDiv,您将创建一个闭包,它指向 3 个 div 的同一对象。最后一张。
关于javascript - 使用 Javascript 动态添加 html 元素和事件处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17845288/