You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

jQuery .each()遍历DOM对象未执行,排查方向有哪些?

问题

我正在MVC解决方案中构建一个用于导航的HTML Partial,所有CSS、HTML和JavaScript都包含在该Partial中。我想通过jQuery的.each()函数遍历导航步骤,为当前页面的导航项添加CSS类current,但这个函数从未执行(调试器命中后直接跳过)。请问我可能哪里出错了?


原代码

JavaScript

var myURL = 'https://example.com/path/sftpaccount'; 
var arrURL = myURL.split('/');
// 最初我用的是 window.location.pathname 而非完整URL
var thisView = arrURL[arrURL.length - 1].toLowerCase();
console.log(thisView);
console.log($('.navStep').length);
$('.navStep').each(function() {
  if (thisView == $(this).data('viewName').toLowerCase()) {
    $(this).addClass('current');
  } else {
    $(this).removeClass('current');
  }
})

CSS

.current { text-decoration: underline;}

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
<div class="row navRow">
  <div class="col-md-3 text-center navStep" data-viewName="sftpaccount" onclick="window.location = '/Integration/SftpAccount';">
    <div class="stepFirst">Step 1</div>
  </div>
  <div class="col-md-3 text-center navStep" data-viewName="sftp_columnmapping" onclick="window.location = '/Integration/Sftp_ColumnMapping';">
    <div class="step">Step 2</div>
  </div>
  <div class="col-md-3 text-center navStep" data-viewName="sftp_documentmapping" onclick="window.location = '/Integration/Sftp_DocumentMapping';">
    <div class="step">Step 3</div>
  </div>
  <div class="col-md-3 text-center navStep" data-viewName="sftp_usermapping" onclick="window.location = '/Integration/Sftp_UserMapping';">
    <div class="stepLast">Step 4</div>
  </div>
</div>

可能的错误原因及修正方案

1. DOM加载顺序问题

你的JS代码可能在.navStep元素渲染完成前就执行了,导致$('.navStep').length为0,循环直接跳过。

修正:将代码包裹在$(document).ready()中,确保DOM完全加载后再执行逻辑:

$(document).ready(function() {
  var myURL = window.location.href; 
  var arrURL = myURL.split('/');
  var thisView = arrURL[arrURL.length - 1].toLowerCase();
  console.log(thisView);
  console.log($('.navStep').length);
  $('.navStep').each(function() {
    // jQuery的data()方法会自动将驼峰属性转为小写键名
    if (thisView == $(this).data('viewname').toLowerCase()) {
      $(this).addClass('current');
    } else {
      $(this).removeClass('current');
    }
  });
});

2. jQuery引入时机错误

如果jQuery脚本是在Partial的HTML结构之后引入,执行自定义JS时$会未定义,代码直接中断,循环自然不会执行。

修正:确保jQuery脚本在自定义JS之前加载,且自定义JS放在HTML结构之后:

<div class="row navRow">
  <!-- 导航项HTML -->
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
<script>
// 自定义JS代码放在这里
$(document).ready(function() {
  // ...逻辑代码
});
</script>

3. 路径匹配逻辑偏差(可选排查)

若使用window.location.pathname时,解析出的thisView和data-viewName格式不匹配(比如包含额外参数、大小写不一致),会导致循环执行但无视觉变化。可以通过console.log打印thisView和$(this).data('viewname')的值确认匹配情况。


内容的提问来源于stack exchange,提问作者Nosnetrom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 16:53:22