所以我得到了以下场景:
$('.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”,我该怎么做呢?
最佳答案
只在循环外保留一个变量:
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
}
此外,语句末尾的分号不是可选的。
关于javascript - 遍历 if,如果为 false 则返回,如果为 true => 停止 if,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9551511/