-->

click Event is not delegated in chrome

2019-07-23 08:46发布

问题:

In my application I create some new elements and append them to the page according to use's operation,

var dv=document.createElement('div');
//set styles for the dv
.....

After create this div element,I will add some event to it:

MyLib.Event.addDomListener(dv,'click',function(e){
    console.info('click');
});
MyLib.Event.addDomListener(dv,'mousedown',function(e){
    console.info('mousedown');
});

This is the generated result in the page(a div contain a img tag and a span tag):

After the page loaded,things get wrong.

If I click the image directly,the 'click' event does not trigger,but the 'mousedown' event does.

If I click the div directly without the image,everything goes well.

It seems that,when I click the image,the 'click' event is not delegated to the div.

But then I copy the final generated code through chrome develop tool,it is something like this:

<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>

Then I copy it to a new .html file,and add the event script:

<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>

Now,both of the two event occur no matter where I click inside the div.

I am really crazy,what is the problem? I do not do anything specially for the generated div.

So I want to know if any of you have meet this problem? Or In which case this kind of exception can happen?


Update:

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;
}

It just for cross-browser use,and notice that the 'mousedown' event works well anyway.

回答1:

I notice that you are using two different methods of attaching the listener between your two examples.

It is always best practice to isolate the possible causes by making things as closely duplicated as possible. Try sticking to the same method of attaching the listener for both tests and this might lead you to some insight.

Also, I don't know what "MyLib" is, but if it is some sort of JS library, the problem could be in that library. Try using the native JS methods or a different library.