2012-03-04 42 views
1

所以我得到了以下的場景:遍歷如果返回,如果假,如果是真的=>停止,如果

$('.menu').find('a').each(function(el, val) { 
    if(window.location.hash !== val.hash) { 
    $('.menu li').first().addClass('active') // we found no valid hash for us, so set first <li> active 
    $('#hash1').show() // and show the first content 
    } else { 
    $(this).parent().addClass('active') // we found an hash, so give its parent <li> an active class 
    $(window.location.hash).show() // can be #hash2, #hash3, whatever 
    return false; // since we found something, stop the if. 
    } 
}); 

現在好了,很明顯,每次我們沒有找到有效的哈希值的時候,我們設置的第一個元素活躍,顯示第一個內容......但我不想要那個。

我希望在if語句進入else語句之前先循環所有元素。然後如果我們什麼也沒找到,請設置第一個元素爲活動狀態並顯示第一個內容。

因爲我循環每個「a」,我該怎麼做?

回答

1

您可以使用.filter()來獲取所需的元素。如果沒有被選中,您將執行默認動作:

var $links = $('.menu').find('a').filter(function() { 
    return window.location.hash === this.hash; 
}); 

if($links.length > 0) { 
    $links.parent().addClass('active'); 
    $(window.location.hash).show(); 
} 
else { 
    $('.menu li').first().addClass('active'); 
    $('#hash1').show(); 
} 

參考.filter

+0

這也很好。現在..這是更快然後$ .each? – 2012-03-04 02:06:24

+0

可能不是,我敢肯定'filter'在內部使用'each'。我只是覺得它有點乾淨,因爲它避免了一個額外的標誌。 – 2012-03-04 02:07:45

+0

只是在jsperf上測試它。他們之間幾乎沒有區別。謝謝! – 2012-03-04 02:17:23

3

只要保持一個變量循環外:

var found = false; 

$('.menu').find('a').each(function(el, val) { 
    if(window.location.hash === val.hash) { 
     $(this).parent().addClass('active'); // we found an hash, so give its parent <li> an active class 
     $(window.location.hash).show(); // can be #hash2, #hash3, whatever 

     found = true; 
    } 
}); 


if(!found) { 
    $('.menu li').first().addClass('active'); // we found no valid hash for us, so set first <li> active 
    $('#hash1').show(); // and show the first content 
} 

此外,在聲明的末尾分號可選。

+0

_「另外,語句末尾的分號不是可選的。」_是的。 (一般情況下,JavaScript中並不是100%,但肯定是100%的代碼中的語句。) – nnnnnn 2012-03-04 01:36:26

+0

@nnnnnn:我重申,*不*可選。是的,口譯員會爲你添加它們。是的,這是「合法的」。它也會造成可怕的代碼。不是可選的;) – Ryan 2012-03-04 01:37:20

+0

http://blog.izs.me/post/2353458699「JavaScript社區中的思想領導者繼續傳播不確定性而不是理解,這是公然不負責任的。」 – 2012-03-04 01:39:15

0

如果你能在英語中更清楚地解釋您的要求,我認爲你會發現JavaScript的結構自然會隨之而來。

在你正在嘗試做以下是我最好的猜測:中「菜單」具有相同.hashwindow.location.hash應該有他們的父母李提出‘積極’,並顯示相應的元素全部錨。如果沒有匹配,則應顯示第一個菜單項「有效」和「#hash1」。

var matched = false; 
$('.menu').find('a').each(function(el, val) { 
    if(window.location.hash === val.hash) { 
    matched = true; 
    $(this).parent().addClass('active'); 
    $(window.location.hash).show(); 
    } 
}); 
if (!matched) { 
    $('.menu li').first().addClass('active'); 
    $('#hash1').show(); 
} 
0
var elm = $(window.location.hash).length ? window.location.hash : '#hash1'; 
$(elm).show(); 
$('a[href$="'+elm+'"]').parent().addClass('active'); 

假設標記爲#hash1作爲其餘部分是相同的,並且有在瀏覽器地址欄中(或無)只有一個散列?