所以我得到了以下的场景:遍历如果返回,如果假,如果是真的=>停止,如果
$('.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