How do I bind a click to an anchor without a framework (javascript)

前端 未结 6 612
难免孤独
难免孤独 2020-12-06 05:23

I know this is easily done in jQuery or any other framework, but that\'s not really the point. How do I go about \'properly\' binding a click event in pure javascript? I kno

6条回答
  •  心在旅途
    2020-12-06 05:29

    The basic way is to use document.getElementById() to find the element and then use addEventListener to listen for the event.

    In your HTML:

    click here
    

    In your JavaScript:

    function myFunc(eventObj) {
      // ...
    }
    
    var myElement = document.getElementById('some-id');
    myElement.addEventListener('click', myFunc);
    

    Or you can use an anonymous function:

    document.getElementyById('some-id').addEventListener('click', function(eventObj) {
      // ...
    });
    

提交回复
热议问题