【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>
addEventListener
和onclick
什么区别?
var h = document.getElementById("a");
h.onclick = dothing1;
h.addEventListener("click", dothing2);
上面的代码一起驻留在单独的.js文件中,并且它们都可以正常工作。
#1楼
JavasSript中'this'
关键字引用的上下文不同。
看下面的代码:
<!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'
对象。
其次,如果您评论btnSubmit.onclick = disable();
并取消注释//btnSubmit.addEventListener('click', disable, false);
您会看到该按钮被禁用,因为通过这种方式,button.onclick事件和onclick事件处理程序之间存在显式绑定。 如果您调试到禁用功能,则可以看到'this'
是指button control
而不是window
。
这是我不喜欢JavaScript的不一致之处。 顺便说一句,如果您使用的是jQuery( $('#btnSubmit').on('click', disable);
),它将使用显式绑定。
#2楼
如果您不太担心浏览器的支持,则可以使用一种方法在事件调用的函数中重新绑定“ 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中运行良好,并且可能存在使“绑定”与其他浏览器兼容的问题。
#3楼
使用内联处理程序与内容安全策略不兼容,因此从该角度来看, addEventListener
方法更加安全。 当然,您可以使用unsafe-inline
启用内联处理程序,但是,顾名思义,这样做并不安全,因为它会带回CSP阻止的所有JavaScript开发。
#4楼
尚未注意到一个细节:现代的桌面浏览器将不同的按钮按下视为AddEventListener('click'
和onclick
的默认AddEventListener('click'
。
- 在Chrome 42和IE11上,
onclick
和AddEventListener
均会在左键和中键单击时触发。 - 在Firefox 38上,
onclick
仅在左键单击时触发,而AddEventListener
单击则在左键,中键和右键单击时触发。
此外,当涉及滚动游标时,跨浏览器的中键点击行为也非常不一致:
- 在Firefox上,总是会触发中点击事件。
- 在Chrome上,如果Middleclick打开或关闭滚动光标,它们将不会触发。
- 在IE上,当滚动光标关闭时会触发,但在打开时不会触发。
还值得注意的是,任何键盘可选择的HTML元素(例如input
“ click”事件也会在选中时触发空格或Enter键。
#5楼
也应该可以通过对原型进行扩展来扩展侦听器(如果我们有对它的引用,并且它不是匿名函数)-或使“ onclick”调用对函数库的调用(调用其他函数的函数)
喜欢
elm.onclick = myFunctionList
function myFunctionList(){
myFunc1();
myFunc2();
}
这意味着我们不必改变onclick调用,只需更改函数myFunctionList()即可完成我们想要的操作,但这使我们无法控制冒泡/捕获阶段,因此对于较新的浏览器应避免使用。
以防万一将来有人找到这个线程...
来源:oschina
链接:https://my.oschina.net/u/3797416/blog/3154754