点击"点击"和onclick

时间:2016-04-30 21:04:16

标签: javascript

点击

之间有什么区别
pyen

并点击

document.getElementById("myBtn").addEventListener("click", displayDate);    

它们都被视为事件吗?为什么我们不能使用点击而不是onclick,反之亦然?

3 个答案:

答案 0 :(得分:8)

区别在于第一个是event listener,第二个是event handler content attribute

事件处理程序内容属性存储internal raw uncompiled handler,它通过event handler processinggetting the current value of the event handler算法生成事件侦听器。

实际上,这会影响范围,例如

(function() { var element = document.body;
  var str = "console.log([typeof foo, typeof bar])";
  var func = function() { console.log([typeof foo, typeof bar]); };
  element.foo = 'foo';
  var bar = 'bar';
  element.setAttribute('onclick', str);
  element.addEventListener('click', func);
  element.click();
  // Event handler content attribute logs ["string", "undefined"]
  // Event listener logs ["undefined", "string"]
})();

我不鼓励使用事件处理程序。它们是旧的回忆,并被事件监听器取代。

答案 1 :(得分:5)

它们是同一个事件,在使用事件监听器分配时,在分配处理程序内联和onclick时只使用一个click

你不能反过来使用它们,因为这是必须要做的,或者他们不会工作。

在MDN阅读更多内容:

答案 2 :(得分:-1)

$("#profile-register #submit").click(function (e) {
        e.preventDefault();
        console.log("I executed")
    })

成功阻止了默认行为,但是下面的代码不能

$("#profile-register #submit").onclick=function (e) {
        e.preventDefault();
        console.log("I executed")
    }

它使用参数重定向表单,您可以在上面的URL框中看到它