Home > Software engineering >  In Jquery, I want to bind some buttons in a loop but failed?
In Jquery, I want to bind some buttons in a loop but failed?

Time:08-20

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?

CodePudding user response:

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);
   });
}

CodePudding user response:

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  data-id="1">1</button>
<button  data-id="2">2</button>
<button  data-id="3">3</button>
<button  data-id="4">4</button>
<button  data-id="5">5</button>

  • Related