English 中文(简体)
这两个添加的 Event 函数有什么区别?
原标题:What s the difference between these two addEvent functions?

这是第一个:

function addEvent(el, type, fn){
    if(el.addEventListener){
        el.addEventListener(type, fn, false);
    }else{
        el[fn] = function(){
            fn.call(el, window.event);
        }
        el.attachEvent( on +type, el[fn]);
    }
}

和第二个:

function addEvent(el, type, fn){
    if(el.addEventListener){
        el.addEventListener(type, fn, false);
    }else{  
        el[ e  + fn] = function(){
            fn.call(el, window.event);
        }
        el.attachEvent( on +type, el[ e +fn]);
    }
}

第二个只是添加一个前缀, 它用什么用?

最佳回答

在我看来,这两种函数似乎都试图做同样的事情:将事件处理器捆绑在一起,其方式在浏览器(即不支持.addEventListener () )的旧 IE 版本)上是一致的。如果有 .addEventListener () 方法可用,则使用这种方法,否则它会创建代理功能,确保回调功能被调时为 this 和事件对象设定适当的值。

在创建元素属性并随后引用该元素属性时,差异仅在 el[fn] el[ e+fn] 中存在:

    el[fn] = function(){
        fn.call(el, window.event);
    }

fn 参数 addEvent () () ) 必须是一个函数引用, 并且我无法确定如果您使用函数引用作为属性名称, 但是我想它基本上在函数上做了 to String () , 并使用结果作为属性名称。 因此, el[ e +fn] 也会做同样的事情, 但是在开头添加 e 。 我看不出“e”有任何特殊的意义。

问题回答

暂无回答




相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签