简体   繁体   中英

srcElement not working in IE9

I've been putting together a lightweight event utility for cross-browser event handling, but have come across a rather high hurdle I can't quite jump over. It's concerning the srcElement property in IE9, which just isn't working for me!

Currently, my utility looks something like this (the srcElement is the 3rd code block):

var bonsallNS = new Object();

bonsallNS.events = {
addEvent: function (node, type, func) {
    if (typeof attachEvent != "undefined") {
        node.attachEvent("on" + type, func);
    } else {

        node.addEventListener(type, func, false);
    }
},
removeEvent: function (node, type, func) {
    if (typeof detachEvent != "undefined") {
        node.detachEvent("on" + type, func);
    } else {

        node.removeEventListener(type, func, false);
    }
},
target: function (e) {
    if (typeof srcElement != "undefined") {
        return window.event.srcElement;
    } else {
        return e.target;
    }
},
preventD: function (e) {
    if (typeof srcElement != "undefined") {
        window.event.returnValue = false;
    } else {
        e.preventDefault();
    }
}
}

Now, using the following test script below works fine in Chrome and Firefox, but returns the evtTarget to be undefined in IE when I try to alert it. I have NO idea why, so any help would be greatly appreciated! See below code:

var gClick = document.getElementById("clickme");
var gCount = 0;

function mssg(e){

var evtTarget = bonsallNS.events.target(e);
alert("it worked, target: " + evtTarget);
gCount++
if (gCount > 2){
    bonsallNS.events.removeEvent(gClick, "click", mssg);
}
}

function setUp(){
bonsallNS.events.addEvent(gClick, "click", mssg);
}

bonsallNS.events.addEvent(window, "load", setUp);

Like I say, everything else works except for the event source in IE!!

The variable srcElement will always be undefined unless it's defined in a higher scope. But it will never refer to event.srcElement .

You can solve this problem in two ways: Either check whether e or e.srcElement are not defined, or whether window.event and window.event.srcElement are defined.

if (typeof e === "undefined" || typeof e.srcElement === "undefined") {
// or
if (typeof window.event !== "undefined" && 
    typeof window.event.srcElement !== "undefined") {

You can also shorten the whole function to:

target: function (e) {
    e = e || window.event;
    return e.target || e.srcElement;
}

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