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

当URL包含特定术语时显示/隐藏页面元素

解决URL包含"/de"时切换元素显示状态的问题

咱们先拆解下你两段代码里的问题,再给出修复后的可行方案:

第一段代码的问题

这段的核心问题是正则表达式写法完全错误:/\/search\///de(window.location) 是不符合JS语法的无效写法,而且你原本要检测的是"/de",这里却写了匹配"/search/"的正则。

修复后的原生JS代码:

window.onload = function () { 
  var de = document.getElementById("german"); 
  var eng = document.getElementById("english"); 
  // 正确检测URL中是否包含"/de"
  if (/\/de/.test(window.location.href)) { 
    de.style.display = "block"; 
    eng.style.display = "none"; 
  } else { 
    de.style.display = "none"; 
    eng.style.display = "block"; 
  } 
}

第二段代码的问题

这段用了jQuery,但结尾缺少闭合的});,导致语法错误,代码根本无法执行。另外既然用了jQuery,其实可以用jQuery选择器简化元素获取,不用混合原生JS写法。

修复后的jQuery代码:

$(document).ready(function() { 
  var $de = $("#german"); 
  var $eng = $("#english"); 
  if (window.location.href.indexOf("/de") > -1) { 
    $de.show(); 
    $eng.hide(); 
  } else { 
    $de.hide(); 
    $eng.show(); 
  }
}); // 补上缺失的闭合括号和分号

额外优化建议

如果你的元素初始状态已经通过CSS设置好(比如默认显示英文、隐藏德文),可以进一步简化代码,减少重复判断:

原生JS优化版:

window.addEventListener('load', function() {
  const hasDePath = window.location.href.includes('/de');
  document.getElementById('german').style.display = hasDePath ? 'block' : 'none';
  document.getElementById('english').style.display = hasDePath ? 'none' : 'block';
});

jQuery优化版:

$(document).ready(function() {
  const hasDePath = window.location.href.includes('/de');
  $('#german').toggle(hasDePath);
  $('#english').toggle(!hasDePath);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 09:42:55