我怎样才能写得更简洁?
这是按钮列表,所有按钮都执行相同的操作,更改一些 css 属性,但在不同的位置
$('#right-panel li:nth-child(1)').click(function() {
$('#pom03par01WraperAbsolute').css('display','block');
$(this).css('background','#adff84');
$('.par01table').css('background','#adff84');
return false;
});
$('#right-panel li:nth-child(2)').click(function() {
$('#pom03par02WraperAbsolute').css('display','block');
$(this).css('background','#adff84');
$('.par02table').css('background','#adff84');
return false;
});
$('#right-panel li:nth-child(3)').click(function() {
$('#pom03par03WraperAbsolute').css('display','block');
$(this).css('background','#adff84');
$('.par03table').css('background','#adff84');
return false;
});
$('#right-panel li:nth-child(4)').click(function() {
$('#pom03par04WraperAbsolute').css('display','block');
$(this).css('background','#adff84');
$('.par04table').css('background','#adff84');
return false;
});
最佳答案
选项 1:
使用for循环
并动态构建选择器:
var numberOfChildren = 4;
for (var i = 1; i <= numberOfChildren; i++) {
$('#right-panel li:nth-child(' + i + ')').click(function() {
$('#pom03par0' + i + 'WraperAbsolute').css('display', 'block');
$(this).css('background', '#adff84');
$('.par0' + i + 'table').css('background', '#adff84');
return false;
});
}
选项 2:
您似乎对每个元素都做了同样的事情。只需为每个元素分配相同的类并通过该类对其进行操作即可。
其他信息
阅读 jQuery Events: Stop (Mis)Using Return False 可能对您也有帮助。 .
关于jquery - 我可以写得更简洁吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9431005/