Bind event to element using pure Javascript

前端 未结 2 1355
一向
一向 2020-12-28 13:24

I\'m writing an API and unfortunately need to avoid any jQuery or 3rd party libraries. How exactly are the events bound to elements through jQuery?

jQuery example:

2条回答
  •  春和景丽
    2020-12-28 14:08

    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.

提交回复
热议问题