【问题标题】:jQuery .each function with if condition works for first element带有if条件的jQuery .each函数适用于第一个元素
【发布时间】:2021-03-17 12:32:58
【问题描述】:

我有 HTML 内容(实际上是这样的 WordPress 插件标签)-

<div class="store-tabs">
        <ul class="list-inline">
            <li><a href="https://example.com/store/">Products</a></li>
            <li><a href="https://example.com/store/reviews">Reviews</a></li>
        </ul>
</div>

如果我在匹配的 URL 上,我正在尝试将“活动”类添加到链接元素。我的问题是该条件仅适用于第一个元素,但第二个元素无法获得该类。这是我的 jQuery -

jQuery(document).ready(function($){
  
  var url      = window.location.href;

  $('.store-tabs .list-inline li a').each(function(){

    var current = $(this).attr('href');

    if (current == url) {
      $(this).addClass('active');
    }

   });

});

更新

代码是正确的,但我的网址末尾没有匹配的斜杠。我已经通过动态添加斜线来修复它(URL 是自动生成的)-

if(current.slice(current.length - 1) != '/') {
      current = current + '/';
    }

谢谢大家:)

【问题讨论】:

  • 你可以试试if (url.indexOf(current) &gt; -1)
  • 我会有两个以上的标签。我相信这只能检查特定值。
  • 请发布您的开发者工具的调试输出,通过将console.log({ current, url }); 添加到您的每个回调中创建。这将帮助我们所有人找到错误并提供所有必要的信息来帮助您。提前致谢!

标签: javascript jquery css wordpress


【解决方案1】:

https://example.com/store/reviews 不等于 https://example.com/store/reviews/。 尝试在 href="https://example.com/store/reviews" 末尾添加“/”

【讨论】:

  • 天哪!这是绝对正确的!结尾的“/”不匹配。
猜你喜欢
  • 2012-06-12
  • 2015-11-03
  • 2012-03-11
  • 2011-12-08
  • 2021-02-28
  • 2021-02-12
  • 2013-01-11
  • 2011-08-25
相关资源
最近更新 更多