Bind event to element using pure Javascript

吃可爱长大的小学妹 提交于 2019-11-30 01:31:22
Dan Tao

Here's a quick answer:

document.getElementById('anchor').addEventListener('click', function() {
  console.log('anchor');
});

Every modern browser supports an entire API for interacting with the DOM through JavaScript without having to modify your HTML. See here for a pretty good bird's eye view: http://overapi.com/javascript

You identify the element by id, in this case anchor, by:

var el = document.getElementById('anchor');

Then you need to assign your click event:

el[window.addEventListener ? 'addEventListener' : 'attachEvent']( window.addEventListener ? 'click' : 'onclick', myClickFunc, false);

And finally, the event's function would be something like:

function myClickFunc()
{
    console.log('anchor');
}

You could simplify it or turn it into a one-liner if you do not need compatibility with older browsers and and a range of browsers, but jQuery does cross-browser compatibility and does its best to give you the functionality you are looking for in as many older browsers as it can.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!