简体   繁体   中英

Why is event.target in my code can't run in firefox?

Why is event.target in my code can't run in firefox?

 <script> 
    document.onmousedown = function(){
     var e = window.event;
     var target = e.srcElement || e.target || e.currentTarget;
     if(target.className == 'box'){
     alert("Yeah");
     }
     }
    </script>



<body>
  <div class="box" style="border:1px dotted #CC3366; width:300px; height:100px;">Click Me!!</div>
  <a href="#" class="box">Link</a>
 </body>

It can run in IE or Chrome but it not in firefox.

Firefox requires the event to be explicitly defined as a parameter of the handler.

You can write something like:

document.onmousedown = function(e) {
    e = e || window.event;
    var target = e.srcElement || e.target || e.currentTarget;
    if (target.className == "box") {
        alert("Yeah");
    }
};

Firefox does not support window.event because it is not part of any standard, Microsoft created it as part of their proprietary event model before events were standardized.

Forgetting these sorts of differences, even the standard DOM is a mess . That is why JS DOM libraries started to be created, they make most tasks dealing with the DOM much easier and smooth over differences in implementation for the event model and other things.

For instance that code could be rewritten with jQuery as

$('.box').mousedown(function(){
  alert("Yeah");
});

Generally speaking, attaching events to the document or body is a bad idea. This jQuery code looks for any elements that have the .box class and attaches the mousedown handler directly to them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM