JavaScript - onClick to get the ID of the clicked button

前端 未结 16 1259
名媛妹妹
名媛妹妹 2020-11-22 05:44

How do find the id of the button which is being clicked?


16条回答
  •  遇见更好的自我
    2020-11-22 06:25

    How to do it without inline JavaScript

    it is generally recommended to avoid inline JavaScript, but rarely is there an example of how to do it.
    Here is my way of attaching events to buttons.
    I'm not entirely happy with how much longer the recommended method is compared to a simple onClick attribute.

    2014 browsers only

    
    
    

    2013 browsers only

    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    Button 4
    
    
    
    

    Cross-browser

    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    Button 4
    
    
    
    

    Cross-browser with jQuery

    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    Button 4
    
    
    
    

    You can run this before the document is ready, clicking the buttons will work because we attach the event to the document.

    Here is a jsfiddle
    For some strange reason the insertHTML function does not work in it even though it works in all my browsers.

    You can always replace insertHTML with document.write if you don't mind it's drawbacks

    
    

    Sources:

    • What are alternatives to document.write?
    • Check if an element contains a class in JavaScript?
    • event.preventDefault() function not working in IE
    • https://gist.github.com/eduardocereto/955642

提交回复
热议问题