在我的应用程序中,我创建了一些新元素并根据用户的操作将它们附加到页面,
var dv=document.createElement('div');
//set styles for the dv
.....
创建此 div 元素后,我将向其添加一些事件:
MyLib.Event.addDomListener(dv,'click',function(e){
console.info('click');
});
MyLib.Event.addDomListener(dv,'mousedown',function(e){
console.info('mousedown');
});
这是页面中生成的结果(一个 div 包含一个 img 标签和一个 span 标签):
页面加载后,事情就出错了。
如果我直接单击图像,click
事件不会触发,但mousedown
事件会触发。
如果我在没有图像的情况下直接单击 div,一切顺利。
似乎,当我单击图像时,该click
事件并未委托给 div。
但是后来我通过 Chrome 开发工具复制了最终生成的代码,它是这样的:
<div id="con" style="position: absolute; border:1px solid red; left: 10px; top: 10px; width: 20px; height: 34px; ">
<img src="http://localhost/MAPALINE/IMAGES/MARKER_LARGE.PNG" id="ov" style="left: 0px; top: 0px; position: relative; width: 20px; height: 34px; ">
<span style="text-align: center; left: 0px; top: 0px; width: 20px; position: absolute; ">1</span>
</div>
然后我将它复制到一个新的 .html 文件中,并添加事件脚本:
<script type="text/javascript">
var con=document.getElementById('con');
con.addEventListener('click',function(e){
console.info('click');
},false);
con.addEventListener('mousedown',function(e){
console.info('mousedown');
},false);
</script>
现在,无论我在 div 内的哪个位置单击,这两个事件都会发生。
我真的疯了,有什么问题?我没有专门为生成的 div 做任何事情。
所以我想知道你们中是否有人遇到过这个问题?或者在哪种情况下会发生这种异常?
更新:
Mylib.Event.addDomListener=function(target,evt,handler){
if(target.addListener){
target.addListener(evt,handler,false);
}else if(target.atttchEvent){
target.attachEvent('on'+evt,handler);
}else
#~ target['on'+evt]=handler;
}
它仅用于跨浏览器使用,请注意该mousedown
事件无论如何都运行良好。