javascript - 遍历 if,如果为 false 则返回,如果为 true => 停止 if

标签 javascript jquery loops if-statement

所以我得到了以下场景:

$('.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/

相关文章:

jquery - 如何找到特定功能的 jQuery 实现

javascript document.domain 和端口号

jquery - 盒子阴影不起作用

javascript - 将原始 html 从 Vue 返回到 Laravel Blade

javascript - 从底部到顶部旋转 Div

python - 在 python 中实现 C 代码循环

javascript - 如何避免从查询中读取行时超时(Phonegap + Javascript)

c++ - 删除所有以//c++ 开头的注释行

javascript - 如果我使用JQuery,是否需要使用BluePrint的ie.css?

javascript - 如何检查是否将完成的 POST 方法提交到数据库,然后在 React-Redux 中重新渲染