JavaScript - onClick to get the ID of the clicked button

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

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


相关标签:
16条回答
  • 2020-11-22 06:20
     <button id="1"class="clickMe"></button>
    
    <button id="2" class="clickMe"></button>
    
    <button id="3" class="clickMe"></button>
    
    
    
    $('.clickMe').live('click',function(){
    
    var clickedID = this.id;
    
    });
    
    0 讨论(0)
  • 2020-11-22 06:23

    You can simply do it this way:

    <input type="button" id="1234" onclick="showId(this.id)" value="click me to show my id"/>
    <script type="text/javascript">
       function showId(obj) {
            var id=obj;
            alert(id);
       }
    

    0 讨论(0)
  • 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

    <button class="btn" id="b1">Button</button>
    <script>
    let OnEvent = (doc) => {
        return {
            on: (event, className, callback) => {
                doc.addEventListener('click', (event)=>{
                    if(!event.target.classList.contains(className)) return;
                    callback.call(event.target, event);
                }, false);
            }
        }
    };
    
    
    OnEvent(document).on('click', 'btn', function (e) {
        window.console.log(this.id, e);
    });
    
    </script>
    

    2013 browsers only

    <!DOCTYPE html>
    <html>
    <head>
    <script>
    (function(doc){
        var hasClass = function(el,className) {
            return el.classList.contains(className);
        }
        doc.addEventListener('click', function(e){
          if(hasClass(e.target, 'click-me')){
              e.preventDefault();
              doSomething.call(e.target, e);
          }
        });
    })(document);
    
    function insertHTML(str){
      var s = document.getElementsByTagName('script'), lastScript = s[s.length-1];
      lastScript.insertAdjacentHTML("beforebegin", str);
    }
    
    function doSomething(event){
      console.log(this.id); // this will be the clicked element
    }
    </script>
    <!--... other head stuff ...-->
    </head>
    <body>
    
    <!--Best if you inject the button element with javascript if you plan to support users with javascript disabled-->
    <script>
    insertHTML('<button class="click-me" id="btn1">Button 1</button>');
    </script>
    
    <!--Use this when you don't care about broken buttons when javascript is disabled.-->
    <!--buttons can be used outside of forms https://stackoverflow.com/a/14461672/175071 -->
    <button class="click-me" id="btn2">Button 2</button>
    <input class="click-me" type="button" value="Button 3" id="btn3">
    
    <!--Use this when you want to lead the user somewhere when javascript is disabled-->
    <a class="click-me" href="/path/to/non-js/action" id="btn4">Button 4</a>
    
    </body>
    </html>
    

    Cross-browser

    <!DOCTYPE html>
    <html>
    <head>
    <script type="text/javascript">
    (function(doc){
        var cb_addEventListener = function(obj, evt, fnc) {
            // W3C model
            if (obj.addEventListener) {
                obj.addEventListener(evt, fnc, false);
                return true;
            } 
            // Microsoft model
            else if (obj.attachEvent) {
                return obj.attachEvent('on' + evt, fnc);
            }
            // Browser don't support W3C or MSFT model, go on with traditional
            else {
                evt = 'on'+evt;
                if(typeof obj[evt] === 'function'){
                    // Object already has a function on traditional
                    // Let's wrap it with our own function inside another function
                    fnc = (function(f1,f2){
                        return function(){
                            f1.apply(this,arguments);
                            f2.apply(this,arguments);
                        }
                    })(obj[evt], fnc);
                }
                obj[evt] = fnc;
                return true;
            }
            return false;
        };
        var hasClass = function(el,className) {
            return (' ' + el.className + ' ').indexOf(' ' + className + ' ') > -1;
        }
    
        cb_addEventListener(doc, 'click', function(e){
          if(hasClass(e.target, 'click-me')){
              e.preventDefault ? e.preventDefault() : e.returnValue = false;
              doSomething.call(e.target, e);
          }
        });
    })(document);
    
    function insertHTML(str){
      var s = document.getElementsByTagName('script'), lastScript = s[s.length-1];
      lastScript.insertAdjacentHTML("beforebegin", str);
    }
    
    function doSomething(event){
      console.log(this.id); // this will be the clicked element
    }
    </script>
    <!--... other head stuff ...-->
    </head>
    <body>
    
    <!--Best if you inject the button element with javascript if you plan to support users with javascript disabled-->
    <script type="text/javascript">
    insertHTML('<button class="click-me" id="btn1">Button 1</button>');
    </script>
    
    <!--Use this when you don't care about broken buttons when javascript is disabled.-->
    <!--buttons can be used outside of forms https://stackoverflow.com/a/14461672/175071 -->
    <button class="click-me" id="btn2">Button 2</button>
    <input class="click-me" type="button" value="Button 3" id="btn3">
    
    <!--Use this when you want to lead the user somewhere when javascript is disabled-->
    <a class="click-me" href="/path/to/non-js/action" id="btn4">Button 4</a>
    
    </body>
    </html>
    

    Cross-browser with jQuery

    <!DOCTYPE html>
    <html>
    <head>
    <script type="text/javascript">
    (function($){
        $(document).on('click', '.click-me', function(e){
          doSomething.call(this, e);
        });
    })(jQuery);
    
    function insertHTML(str){
      var s = document.getElementsByTagName('script'), lastScript = s[s.length-1];
      lastScript.insertAdjacentHTML("beforebegin", str);
    }
    
    function doSomething(event){
      console.log(this.id); // this will be the clicked element
    }
    </script>
    <!--... other head stuff ...-->
    </head>
    <body>
    
    <!--Best if you inject the button element with javascript if you plan to support users with javascript disabled-->
    <script type="text/javascript">
    insertHTML('<button class="click-me" id="btn1">Button 1</button>');
    </script>
    
    <!--Use this when you don't care about broken buttons when javascript is disabled.-->
    <!--buttons can be used outside of forms https://stackoverflow.com/a/14461672/175071 -->
    <button class="click-me" id="btn2">Button 2</button>
    <input class="click-me" type="button" value="Button 3" id="btn3">
    
    <!--Use this when you want to lead the user somewhere when javascript is disabled-->
    <a class="click-me" href="/path/to/non-js/action" id="btn4">Button 4</a>
    
    </body>
    </html>
    

    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

    <script>
    document.write('<button class="click-me" id="btn1">Button 1</button>');
    </script>
    

    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
    0 讨论(0)
  • 2020-11-22 06:25

    This will log the id of the element that's been clicked: addFields.

    <button id="addFields" onclick="addFields()">+</button>
    
    <script>
    
    function addFields(){ 
        console.log(event.toElement.id)
    }
    
    </script>
    
    0 讨论(0)
  • 2020-11-22 06:27

    With pure javascript you can do the following:

    var buttons = document.getElementsByTagName("button");
    var buttonsCount = buttons.length;
    for (var i = 0; i < buttonsCount; i += 1) {
        buttons[i].onclick = function(e) {
            alert(this.id);
        };
    }​
    

    check it On JsFiddle

    0 讨论(0)
  • 2020-11-22 06:28

    (I think the id attribute needs to start with a letter. Could be wrong.)

    You could go for event delegation...

    <div onClick="reply_click()">
        <button id="1"></button>
        <button id="2"></button>
        <button id="3"></button>
    </div>
    
    function reply_click(e) {
        e = e || window.event;
        e = e.target || e.srcElement;
        if (e.nodeName === 'BUTTON') {
            alert(e.id);
        }
    }
    

    ...but that requires you to be relatively comfortable with the wacky event model.

    0 讨论(0)
提交回复
热议问题