我在表单中添加了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>
答案 0 :(得分:0)
尝试
ClickMe(this);
使用currentDiv,您将创建一个闭包,它指向3个div的同一个对象。最后一个。