所以我得到了以下的場景:遍歷如果返回,如果假,如果是真的=>停止,如果
$('.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」,我該怎麼做?
這也很好。現在..這是更快然後$ .each? – 2012-03-04 02:06:24
可能不是,我敢肯定'filter'在內部使用'each'。我只是覺得它有點乾淨,因爲它避免了一個額外的標誌。 – 2012-03-04 02:07:45
只是在jsperf上測試它。他們之間幾乎沒有區別。謝謝! – 2012-03-04 02:17:23