addEventListener和onclick有什么区别?

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

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


当前回答

let element = document.queryselector('id or classname'); 
element.addeventlistiner('click',()=>{
  do work
})

<button onclick="click()">click</click>`
function click(){
  do work
};

其他回答

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

但onclick没有,只有假的

在这个回答中,我将描述定义DOM事件处理程序的三种方法。

element.addEventListener()

代码示例:

const element = document.querySelector('a'); 元素。addEventListener('click', event => event. preventdefault (), true); <a href="//google.com">试着点击这个链接

addeventlistener()有多个优点:

Allows you to register unlimited events handlers and remove them with element.removeEventListener(). Has useCapture parameter, which indicates whether you'd like to handle event in its capturing or bubbling phase. See: Unable to understand useCapture attribute in addEventListener. Cares about semantics. Basically, it makes registering event handlers more explicit. For a beginner, a function call makes it obvious that something happens, whereas assigning event to some property of DOM element is at least not intuitive. Allows you to separate document structure (HTML) and logic (JavaScript). In tiny web applications it may not seem to matter, but it does matter with any bigger project. It's way much easier to maintain a project which separates structure and logic than a project which doesn't. Eliminates confusion with correct event names. Due to using inline event listeners or assigning event listeners to .onevent properties of DOM elements, lots of inexperienced JavaScript programmers thinks that the event name is for example onclick or onload. on is not a part of event name. Correct event names are click and load, and that's how event names are passed to .addEventListener(). Works in almost all browser. If you still have to support IE <= 8, you can use a polyfill from MDN.

元素。Onevent = function(){}(例如onclick, onload)

代码示例:

const element = document.querySelector('a'); 元素。onclick = event => event. preventdefault (); <a href="//google.com">试着点击这个链接

这是在DOM 0中注册事件处理程序的一种方法。现在不鼓励这样做,因为:

Allows you to register only one event handler. Also removing the assigned handler is not intuitive, because to remove event handler assigned using this method, you have to revert onevent property back to its initial state (i.e. null). Doesn't respond to errors appropriately. For example, if you by mistake assign a string to window.onload, for example: window.onload = "test";, it won't throw any errors. Your code wouldn't work and it would be really hard to find out why. .addEventListener() however, would throw error (at least in Firefox): TypeError: Argument 2 of EventTarget.addEventListener is not an object. Doesn't provide a way to choose if you want to handle event in its capturing or bubbling phase.

内联事件处理程序(onevent HTML属性)

代码示例:

<a href="//google.com" onclick="event.preventDefault();>试着点击这个链接

类似于element。Onevent,现在不鼓励了。除了那个元素的问题。Onevent有,它:

Is a potential security issue, because it makes XSS much more harmful. Nowadays websites should send proper Content-Security-Policy HTTP header to block inline scripts and allow external scripts only from trusted domains. See How does Content Security Policy work? Doesn't separate document structure and logic. If you generate your page with a server-side script, and for example you generate a hundred links, each with the same inline event handler, your code would be much longer than if the event handler was defined only once. That means the client would have to download more content, and in result your website would be slower.

另请参阅

EventTarget.addEventListener()文档(MDN) EventTarget.removeEventListener()文档(MDN) onclick vs addEventListener Dom-events标记wiki

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

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

onclick基本上是一个addEventListener,当元素被单击时,它专门执行一个函数。当你有一个做简单操作的按钮时,它很有用,比如计算器按钮。addEventlistener可以用于很多事情,比如在加载DOM或所有内容时执行一个操作,类似于window。Onload,但有更多的控制。

注意,实际上可以使用内联使用多个事件,或者至少可以使用onclick,用分号分隔每个函数,例如....

我不会写一个内联函数,因为你可能会有潜在的问题,这将是混乱的imo。只需使用它来调用脚本文件中已经完成的函数。

你用哪一个取决于你想要什么。addEventListener用于复杂操作,onclick用于简单操作。我见过一些项目没有为元素附加一个特定的事件监听器,而是实现了一个更全局的事件监听器,它将确定是否点击了按钮,并根据所按的按钮执行某些任务。在我看来,这可能会导致潜在的问题,尽管很小,可能,资源浪费,如果事件监听器必须处理每一个点击

如果你不太担心浏览器的支持,有一种方法可以在事件调用的函数中重新绑定'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上运行得很好,并且可能有一些关于“绑定”与其他浏览器兼容的问题。