jquery - 我可以写得更简洁吗?

标签 jquery optimization

我怎样才能写得更简洁?

这是按钮列表,所有按钮都执行相同的操作,更改一些 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/

相关文章:

CSS分辨率优化?

javascript - jQuery 在 remove() 之后检查输入是否存在

javascript - Jquery 在调整大小时忽略 if 语句

javascript - 使用内置 jQuery 在默认设置下发送 ajax 表单数据

algorithm - 获得超过 2 个目标的帕累托前沿

java - 如何更快地阅读 BufferedReader

java - 使用 Java 函数式编程简化 if-else 条件

performance - 性能总是重要的吗?

JavaScript 在 IE9 中随机失败/包含 DIV 的 FORM 标记在 IE9 中过早关闭

javascript - 内部选择使 slidedown div(父级)消失