我在表单中添加了 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>