如何重构这段代码,使其包含较少的复制粘贴代码?
$("#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();
});
Run Code Online (Sandbox Code Playgroud)
我可以在这里使用循环来最小化代码或者一些jQuery吗?
我试过了:
for (i = 1; i <= 4; i++) {
$("#hnv_" + i).click(function (e) {
alert(i);
});
}
Run Code Online (Sandbox Code Playgroud)
但最后..警报总是显示5
tym*_*eJV 12
是,
$("[id^='hnv_']").click(function(e) {
var number = Number(this.id.split("_")[1]);
manipulate(number);
e.stopPropagation();
});
Run Code Online (Sandbox Code Playgroud)
将您的HTML更改为:
<div class="hnv" data-hnv="1">...</div>
<div class="hnv" data-hnv="2">...</div>
and so on
Run Code Online (Sandbox Code Playgroud)
然后将jQuery更改为:
$(".hnv").click(function(e) {
manipulate($(this).data("hnv"));
e.stopPropagation();
}
Run Code Online (Sandbox Code Playgroud)
如果你想用for循环来做,你必须使用立即执行的函数捕获闭包中的索引:
for (var i = 1; i <= 4; i++)
{
(function (i) {
$("#hnv_" + i).click(function(e){
manipulate(i);
e.stopPropagation();
})
})(i);
}
Run Code Online (Sandbox Code Playgroud)
请参阅循环内的JavaScript闭包 - 简单的实际示例,用于解释为什么循环不起作用,并且需要额外的功能.
| 归档时间: |
|
| 查看次数: |
225 次 |
| 最近记录: |