Q:

How to use for loop to add all buttons' click event?

Suppose there are 5 buttons. 
When each button clicks, it shows the alert box of the button's value. For instance, when I click Button 2, it shows the alert box of "You click Button 2"; when I click Button 4, it shows the alert box of "You click Button 4."
Below is the traditional way to practice it:
<script>
$(function(){
    $("#b0").click(function(){
        alert("You click Button 0");
    });
    $("#b1").click(function(){
        alert("You click Button 1");
    });
    $("#b2").click(function(){
        alert("You click Button 2");
    });
    $("#b3").click(function(){
        alert("You click Button 3");
    });
    $("#b4").click(function(){
        alert("You click Button 4");
    });
});
</script>

<button id="b0">Button 0</button>
<button id="b1">Button 1</button>
<button id="b2">Button 2</button>
<button id="b3">Button 3</button>
<button id="b4">Button 4</button>

But it is too inefficient and unprofessional, so I changed it like below:
<script>
$(function(){
    for(i=0;i<5;i++){
        $("#b"+i).click(function(){
            alert("You click Button "+i);
        });
    }
});
</script>

<button id="b0">Button 0</button>
<button id="b1">Button 1</button>
<button id="b2">Button 2</button>
<button id="b3">Button 3</button>
<button id="b4">Button 4</button>

After changing, it always shows "You click Button 5." How can I solve this question using for loop?

A:

You are always firing the value of variable i, after the for loop the value will be 5. So use a self calling function with argument i. 

$(function() {
  for (i = 0; i < 5; i++) {
    (function(i) {
      $("#b" + i).click(function() {
        alert("You click Button " + i);
      });
    })(i);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="b0">Button 0</button>
<button id="b1">Button 1</button>
<button id="b2">Button 2</button>
<button id="b3">Button 3</button>
<button id="b4">Button 4</button>

Or in latest browser use let for block scope level local variable value

$(function() {
  "use strict";
  for (let i = 0; i < 5; i++) {
    $("#b" + i).click(function() {
      alert("You click Button " + i);
    });
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="b0">Button 0</button>
<button id="b1">Button 1</button>
<button id="b2">Button 2</button>
<button id="b3">Button 3</button>
<button id="b4">Button 4</button>

Or you can use index() method and attribute start selector

$(function() {
  var $sel = $('[id^=b]');
  $sel.click(function() {
    alert("You click Button " + $sel.index(this));
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="b0">Button 0</button>
<button id="b1">Button 1</button>
<button id="b2">Button 2</button>
<button id="b3">Button 3</button>
<button id="b4">Button 4</button>

