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

前端 未结 6 614
难免孤独
难免孤独 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:45

    If you need to assign only one click event, you can assign onclick:

    If you have an ID:

    myAnchor = document.getElementById("Anchor");
    myAnchor.onclick = function() { myFunc(); return false; }
    

    you can also walk through all anchors:

    anchors = document.getElementsByTagName("a");
    
    for (var i = 0; i < anchors.length; i++) {   
    
     anchors[i].onclick = .....
    
    }
    

    There's also a document.getElementsByClassName to simulate jQuery's class selector but it is not supported by all browsers.

    If it could be that you need to assign multiple events on one element, go with addEventListener shown by @Jordan and @David Dorward.

提交回复
热议问题