开发者

JavaScript preventDefault not working, neither does return false;

I've searched this question in Stack Overflow before posting it, but none of the posts found seem to work for me.

I have this:

function addEvent(elm, evType, fn) {
    if (elm.addEventListener) {
        elm.addEventListener(evType, fn, false);
        return true;
    }
    else if (elm.attachEvent) {
        var r = elm.attachEvent('on' + evType, fn);
        return r;
    }
    else {
        elm['on' + evType] = fn;
    }
}

and I do this:

var el = document.getElementById('myLink');

addEvent(el, "click", function(event){
         alert('testing');
        if(event.preventDefault){
            event.preventDefault;
        }
         if (event.stopPropagation) {
            event.stopPropagation();
         }
        return false;
    });

where myLink is:

<a 开发者_JS百科href="http://www.google.com" id="myLink">Click me</a>

but when I click the link, it doesn't stop the default event action. I've tested on IE, Firefox and Chrome, with no result.

Any ideas please?


There are a couple of errors in the code:

addEvent(el, "click", function(event){ // event will be undefined in IE
    event = event || window.event; // fallback to window.event in IE

    alert('testing');
    if(event.preventDefault){
        event.preventDefault(); // () was missing here
    }
    if (event.stopPropagation) {
        event.stopPropagation();
    }
    return false;
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜