jquery

在 jQuery 中,.data() 方法对 data-* 属性的读取遵循严格的命名规范化规则:*所有 `data-属性名在 DOM 中必须使用短横线分隔(kebab-case),jQuery 才能正确映射为驼峰式 JavaScript 键名**。而直接使用驼峰写法(如data-viewName)属于非法 HTML 属性命名,浏览器虽会容忍,但 jQuery 内部会将其统一转为全小写('viewname'),导致$(this).data('viewName')返回undefined,进而使整个.each()循环中的判断逻辑失效(undefined.toLowerCase()` 报错或恒为 false)。
✅ 正确做法是:
修改后的 HTML(关键:data-view-name 替代 data-viewName):
Step 1 Step 2
对应 JavaScript(使用 'view-name' 或 'viewName' 均可,推荐语义清晰的 'viewName'):
var myURL = window.location.pathname; // ✅ 推荐用 pathname,避免协议/域名干扰
var arrURL = myURL.split('/');
var thisView = arrURL[arrURL.length - 1].toLowerCase();
console.log('Current view:', thisView);
console.log('Nav items found:', $('.navStep').length);
$('.navStep').each(function() {
// ✅ 正确:jQuery 自动将 data-view-name 映射为 'viewName'
var viewName = $(this).data('viewName'); // 或 .data('view-name')
if (thisView === viewName?.toLowerCase()) {
$(this).addClass('current');
} else {
$(this).removeClass('current');
}
});⚠️ 注意事项: