2012-03-04 86 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作为其余部分是相同的,并且有在浏览器地址栏中(或无)只有一个散列?