jQuery selector in a loop
Hi,
I wrote a simple code:
-
$(document).ready(function() {
$("#font-small").click(function() { alert('xx-small'); });
$("#font-normal").click(function() { alert('x-small'); });
$("#font-big").click(function() { alert('small'); });
});
The I decided to refactor it as:
-
$(document).ready(function() {
var buttons = Array();
buttons["#font-small"] = "xx-small";
buttons["#font-normal"] = "x-small";
buttons["#font-big"] = "small";
for (var id in buttons) {
$(id).click(function() { alert(buttons[id]); });
}
}
The problem is, no matter which '#font-...' I click, I always get an alert message "small". I'm new to jQuery and JS, so can anybody explain me why the second piece of code doesn't work as the first one?