簡體   English   中英

jQuery重構

[英]jQuery refactoring

我經常花10到20分鍾的時間查看jQuery片段,以找到縮短其中代碼的方法。

現在,我一直在不停地查看這段代碼,但只想知道人們將如何重構它,或者是否會重構。

$("#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();
});

這更多是出於好奇的問題,在我試圖提高我的jQuery編碼技能時,我會哭着尋求幫助。

/ *編輯

鏈接附件jsFiddle

您所有美妙建議的最終結果都是。

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");

我將其重構如下。 無需每次都制作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();
    })

我會重構選擇器,因此遍歷Dom的成本會降低。 就像這樣:

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();
});

我個人認為這段代碼可以,但是可以重構$("#tabs div").hide().first().show(); 只是為了使其更具可讀性,也許是:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM