How can I reduce the copy-paste code? Refactor?
javascript, jquery
Solution
Yes,
$("[id^='hnv_']").click(function(e) {
var number = Number(this.id.split("_")[1]);
manipulate(number);
e.stopPropagation();
});
Problem
How can I refactor this piece of code so it contains less copy-paste code? ``` $("#hnv_4").click(function(e){ manipulate(4); e.stopPropagation(); }); $("#hnv_3").click(function(e){ manipulate(3); e.stopPropagation(); }); $("#hnv_2").click(function(e){ manipulate(2); e.stopPropagation(); }); $("#hnv_1").click(function(e){ manipulate(1); e.stopPropagation(); }); ``` Can I use a loop here to minimize the code or maybe some jQuery? I tried: ``` for (i = 1; i <= 4; i++) { $("#hnv_" + i).click(function (e) { alert(i); }); } ``` but at the end .. alert shows 5 always