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?