JavaScript - onClick to get the ID of the clicked button

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

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


相关标签:
16条回答
  • 2020-11-22 06:30

    You need to send the ID as the function parameters. Do it like this:

    <button id="1" onClick="reply_click(this.id)">B1</button>
    <button id="2" onClick="reply_click(this.id)">B2</button>
    <button id="3" onClick="reply_click(this.id)">B3</button>
        
    <script type="text/javascript">
      function reply_click(clicked_id)
      {
          alert(clicked_id);
      }
    </script>

    This will send the ID this.id as clicked_id which you can use in your function. See it in action here.

    0 讨论(0)
  • 2020-11-22 06:31
    <button id="1" onClick="reply_click()"></button>
    <button id="2" onClick="reply_click()"></button>
    <button id="3" onClick="reply_click()"></button>
    
    function reply_click()
    {
       console.log(window.event.target.id)
    }
    
    0 讨论(0)
  • 2020-11-22 06:32
    <button id="1" class="clickMe"></button>
    <button id="2" class="clickMe"></button>
    <button id="3" class="clickMe"></button>
    
    <script>
    $('.clickMe').click(function(){
        alert(this.id);
    });
    </script>
    
    0 讨论(0)
  • 2020-11-22 06:32

    This is improvement of Prateek answer - event is pass by parameter so reply_click not need to use global variable (and as far no body presents this variant)

    function reply_click(e) {
      console.log(e.target.id);
    }
    <button id="1" onClick="reply_click(event)">B1</button>
    <button id="2" onClick="reply_click(event)">B2</button>
    <button id="3" onClick="reply_click(event)">B3</button>

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