addEventListener和onclick有什么区别?

var h = document.getElementById("a");
h.onclick = dothing1;
h.addEventListener("click", dothing2);

上面的代码一起驻留在一个单独的.js文件中,它们都可以完美地工作。


当前回答

也可以通过对侦听器进行原型化(如果我们有对它的引用,而且它不是匿名函数)来扩展侦听器,或者使onclick调用成为对函数库的调用(函数调用其他函数)。

如:

elm.onclick = myFunctionList;
function myFunctionList(){
    myFunc1();
    myFunc2();
}

这意味着我们永远不需要改变onclick调用,只需要改变myFunctionList()函数来做任何我们想做的事情,但这让我们无法控制冒泡/捕获阶段,所以应该避免在新浏览器中使用。

其他回答

如果你不太担心浏览器的支持,有一种方法可以在事件调用的函数中重新绑定'this'引用。它通常指向在函数执行时生成事件的元素,这并不总是您想要的。棘手的部分是同时能够删除相同的事件侦听器,如本例所示:http://jsfiddle.net/roenbaeck/vBYu3/

/*
    Testing that the function returned from bind is rereferenceable, 
    such that it can be added and removed as an event listener.
*/
function MyImportantCalloutToYou(message, otherMessage) {
    // the following is necessary as calling bind again does 
    // not return the same function, so instead we replace the 
    // original function with the one bound to this instance
    this.swap = this.swap.bind(this); 
    this.element = document.createElement('div');
    this.element.addEventListener('click', this.swap, false);
    document.body.appendChild(this.element);
}
MyImportantCalloutToYou.prototype = {
    element: null,
    swap: function() {
        // now this function can be properly removed 
        this.element.removeEventListener('click', this.swap, false);           
    }
}

上面的代码在Chrome上运行得很好,并且可能有一些关于“绑定”与其他浏览器兼容的问题。

据我所知,DOM“加载”事件仍然只发挥非常有限的作用。这意味着它只会触发窗口对象,图像和<script>元素。直接onload赋值也是如此。这两者在技术上没有区别。也许.onload =具有更好的跨浏览器可用性。

但是,您不能将加载事件分配给<div>或<span>元素等。

在我的Visual Studio代码中,addEventListener对事件有真实的智能感知

但onclick没有,只有假的

“this”关键字在JavasSript中引用的上下文是不同的。

请看下面的代码:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>

</head>
<body>
    <input id="btnSubmit" type="button" value="Submit" />
    <script>
        function disable() {
            this.disabled = true;
        }
        var btnSubmit = document.getElementById('btnSubmit');
        btnSubmit.onclick = disable();
        //btnSubmit.addEventListener('click', disable, false);
    </script>
</body>
</html>

它的功能非常简单。当您点击该按钮时,该按钮将自动禁用。

首先,当您尝试以这种方式按钮连接事件时。Onclick = function(), 点击按钮会触发Onclick事件,但是,按钮不会被禁用,因为按钮之间没有显式的绑定。Onclick和Onclick事件处理器。如果你调试看到'this'对象,你可以看到它指向'window'对象。

其次,如果你评论btnSubmit。Onclick =禁用();和取消 / / btnSubmit。addEventListener('点击',禁用,false);您可以看到按钮是禁用的,因为通过这种方式,按钮之间有显式绑定。点击事件和点击事件处理程序。如果你调试为禁用功能,你可以看到“this”指的是按钮控件而不是窗口。

这是我不喜欢JavaScript不一致的地方。 顺便说一句,如果你使用jQuery($('#btnSubmit')。On ('click', disable);),它使用显式绑定。

虽然onclick可以在所有浏览器中工作,但addEventListener不能在旧版本的Internet Explorer中工作,后者使用attachEvent代替。

onclick的缺点是只能有一个事件处理程序,而其他两个将触发所有注册的回调。