Javascript preventDefault无效,也不返回false;

时间:2010-11-24 01:22:01

标签: javascript events javascript-events

我在发布之前已经在stackoverflow中搜索了这个问题,但是任何一个帖子似乎对我有用:(

我有这个:

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

我这样做:

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

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

myLink是..

<a href="http://www.google.com" id="myLink">Click me</a>

但是当我点击de link时,它并没有停止默认的事件动作...我已经在IE,FF和Chrome上测试过,没有结果......

任何想法,请?谢谢......

1 个答案:

答案 0 :(得分:5)

代码中有一些错误:

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