简体   繁体   English

jQuery重构

[英]jQuery refactoring

I often spend 10-20 minutes looking at pieces of jQuery to find a way of shortening the code that's there. 我经常花10到20分钟的时间查看jQuery片段,以找到缩短其中代码的方法。

Now this piece of code I've been looking at time and time again but just want to know how people would go about refactoring it or if indeed they would. 现在,我一直在不停地查看这段代码,但只想知道人们将如何重构它,或者是否会重构。

$("#tabs ul li").first().addClass("activeTab");
$("#tabs div").hide().first().show();
$("#tabs ul li a").click(function(){
    $("#tabs div").hide();
    $("#tabs").find($(this).attr('href')).show();
});

This is more a question of curiosity that a cry for help as I'm trying to better my coding skills in jQuery. 这更多是出于好奇的问题,在我试图提高我的jQuery编码技能时,我会哭着寻求帮助。

/* EDIT / *编辑

Link attached jsFiddle 链接附件jsFiddle

End Result from all your fabulous suggestions is. 您所有美妙建议的最终结果都是。

var $c = $("#tabs"), $t = $c.find("li"), $d = $c.find("div");
$d.not(":first").hide();
$t.find("a").click(function() {
    $d.hide().filter($(this).attr('href')).show();
}).closest("li").first().addClass("activeTab");

I would refactor this as follows. 我将其重构如下。 There is no need to make jQuery object each time, make a reference to it for future use. 无需每次都制作jQuery对象,对其进行引用以供将来使用。

    var $tabs = $("#tabs");

    $tabs.find("li:first").addClass("activeTab");
    $tabs.find('div').not(':first').hide();
    $tabs.find("a").click(function() {
        $("#tabs div").hide().filter($(this).attr('href')).show();
    })

I would refactor the selectors, so traversing the Dom would be less costly. 我会重构选择器,因此遍历Dom的成本会降低。 It would be something like: 就像这样:

var $tabsControl = $("#tabs"),
    $tabs = $tabsControl.find("ul > li"),
    $tabsContent = $tabsControl.find("div");

$tabs.first().addClass("activeTab");
$tabsContent.hide().first().show();
$tabs.find("a").click(function() {
    $tabsContent.hide();
    $tabsControl.find($(this).attr("href")).show();
});

I personally think this code is OK, but would refactor $("#tabs div").hide().first().show(); 我个人认为这段代码可以,但是可以重构$("#tabs div").hide().first().show(); just to make it more readable, maybe: 只是为了使其更具可读性,也许是:

$("#tabs div").not(":first").hide();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM