ruby.none 的 javascript 替代品?

标签 javascript boolean iteration conditional-statements

如果没有满足条件,我如何迭代并做某事。对于 Ruby 中的上下文,我可以执行 some_array.none?{|t| t == "something"} 并得到一个 boolean 值。

在 js 中,我尝试使用 [href] 属性迭代所有元素,如果没有“active”类,则执行某些操作

$("[href]").each(function() {
    if (this.href == window.location.href) {
        $(this).addClass("active");
    }
});

我执行上述操作来设置事件链接的样式,但我希望将其中一个链接设置为事件(如果其他链接均不活动)。我是 js 新手,所以我确信可能有更好的方法。

最佳答案

不能将选择器条件移到 jQuery 选择器中,然后测试选择器长度吗?

var selector = $("[href=" + window.location.href + "]");
selector.each(function() {
    $(this).addClass("active");
});

if(selector.length == 0) {
    $("[href='/snippets/new/]").addClass("active");
}

关于ruby.none 的 javascript 替代品?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50140877/

相关文章:

excel - 在 VBA 中返回 boolean 值

python - 为什么这个 Python boolean 比较返回一个三元组?

php - RecursiveDirectoryIterator 在 "Too many open files"上抛出 UnexpectedValueException

javascript - jQuery 在两个类之间滚动切换

javascript - 删除某个位置的字符,Codemirror

javascript - SAPUI5 中的 jQuery 日期选择器

javascript - for 循环中的 Nightwatch 执行命令出现乱序

javascript - css 中的动态或自适应类

java - 很难在我的代码中找到错误

python - 为什么一个代码比其他代码更快,即使迭代次数更多?