addEventListener
和onclick
什么区别? html
var h = document.getElementById("a"); h.onclick = dothing1; h.addEventListener("click", dothing2);
上面的代码一块儿驻留在单独的.js文件中,而且它们均可以正常工做。 浏览器
JavasSript中'this'
关键字引用的上下文不一样。 安全
看下面的代码: app
<!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>
它的做用很是简单。 当您单击该按钮时,该按钮将被自动禁用。 函数
首先,当您尝试以这种方式button.onclick = function(),
事件button.onclick = function(),
将经过单击按钮来触发onclick事件,可是不会禁用该按钮,由于button.onclick和onclick事件之间没有显式绑定处理程序。 若是调试时看到'this'
对象,则能够看到它指向'window'
对象。 this
其次,若是您评论btnSubmit.onclick = disable();
并取消注释//btnSubmit.addEventListener('click', disable, false);
您会看到该按钮被禁用,由于经过这种方式,button.onclick事件和onclick事件处理程序之间存在显式绑定。 若是您调试到禁用功能,则能够看到'this'
是指button control
而不是window
。 spa
这是我不喜欢JavaScript的不一致之处。 顺便说一句,若是您使用的是jQuery( $('#btnSubmit').on('click', disable);
),它将使用显式绑定。 .net
若是您不太担忧浏览器的支持,则可使用一种方法在事件调用的函数中从新绑定“ this”引用。 一般,它会指向函数执行时生成事件的元素,而这并不老是您想要的。 棘手的部分是要同时可以删除彻底相同的事件侦听器,如本例所示: http : //jsfiddle.net/roenbaeck/vBYu3/ prototype
/* 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中运行良好,而且可能存在使“绑定”与其余浏览器兼容的问题。 线程
使用内联处理程序与内容安全策略不兼容,所以从该角度来看, addEventListener
方法更加安全。 固然,您可使用unsafe-inline
启用内联处理程序,可是,顾名思义,这样作并不安全,由于它会带回CSP阻止的全部JavaScript开发。
还没有注意到一个细节:现代的桌面浏览器将不一样的按钮按下视为AddEventListener('click'
和onclick
的默认AddEventListener('click'
。
onclick
和AddEventListener
均会在左键和中键单击时触发。 onclick
仅在左键单击时触发,而AddEventListener
单击则在左键,中键和右键单击时触发。 此外,当涉及滚动游标时,跨浏览器的中键点击行为也很是不一致:
还值得注意的是,任何键盘可选择的HTML元素(例如input
“ click”事件也会在选中时触发空格或Enter键。
也应该能够经过对原型进行扩展来扩展侦听器(若是咱们有对它的引用,而且它不是匿名函数)-或使“ onclick”调用对函数库的调用(调用其余函数的函数)
喜欢
elm.onclick = myFunctionList function myFunctionList(){ myFunc1(); myFunc2(); }
这意味着咱们没必要改变onclick调用,只需更改函数myFunctionList()便可完成咱们想要的操做,但这使咱们没法控制冒泡/捕获阶段,所以对于较新的浏览器应避免使用。
以防万一未来有人找到这个线程...