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
If you want to print only the id of the clicked button just do something like
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.