How to add click event to an element?

前端 未结 4 758

I would like to add a click event in plain JavaScript (without using jQuery) to an element like this, so I don\'t have an id but a class:



        
4条回答
  •  抹茶落季
    2020-11-27 08:58

    If you don't have an id and don't have any selector library and you want it to work in older browsers, then it takes a bit more work. If you can put an id on it, it's quite simple. If not, it takes more code:

    var links = document.getElementsByClassName("MyClass");
    links[0].onclick = function() {
        // put your click handling code here
        // return(false) if you don't want default click behavior for the link
    }
    

    Since getElementsByClassName is not universally available in older browsers, you would need a shim to implement it when not present. Or, you could get all the links in your document with:

    var links = document.getElementsByTagName("a");
    

    and then cycle through that list until you find the one you want (perhaps checking the class name).

    If you can put an ID on the link:

    Yummy
    

    Then, it just takes this code:

    document.getElementById("specialLink").onclick = function() {
        // add code here
    }
    

    If you're going to do this regularly, the adding an event listener is a little more extensible than using the onclick property, but if you don't have any framework, then you need a function for adding an event listener that handles older versions of IE.

提交回复
热议问题