skip to Main Content

I can alert each button’s id by doing so.

$(function () {
  bind_button();
});
function bind_button() {
  var len = $(".btn-sm").length;
  for(var i = 0; i < len; i ++ ){
    alert($(".btn-sm")[i].id);
  }
}

But when I want to bind the button with its id…

$(function () {
  bind_button();
});
function bind_button() {
  var len = $(".btn-sm").length;
  for(var i = 0; i < len; i ++ ){
    $(".btn-sm")[i].click(function (){
      alert($(".btn-sm")[i].id);
    });
  }
}

When I click the button, no alert appears.

Anyone knows why? And anyone knows how can I bind successfully?

2

Answers


  1. If you want to print only the id of the clicked button just do something like

    function bind_button() {
       $(".btn-sm").click(function(){
          alert(this.id);
       });
    }
    
    Login or Signup to reply.
  2. It’s not clear why you need the loop at all. Why not get the buttons, and assign listeners to them all at once?

    Note: I’ve used data attributes in this example.

    $(function () {
      $('.btn-sm').click(function () {
        console.log($(this).data('id'));
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <button class="btn-sm" data-id="1">1</button>
    <button class="btn-sm" data-id="2">2</button>
    <button class="btn-sm" data-id="3">3</button>
    <button class="btn-sm" data-id="4">4</button>
    <button class="btn-sm" data-id="5">5</button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search