如何通过if/else语句根据URL调用不同的JS脚本
你的代码不可行
你贴的这段代码没法正常运行,原因很简单:在JavaScript代码块里直接写<script>标签属于语法错误,JS引擎根本识别不了这种HTML语法。
要实现根据URL路径加载不同脚本的需求,得用JavaScript的DOM API动态创建脚本元素,下面是可行的写法:
写法一(三元表达式简化版)
const script = document.createElement('script'); script.type = 'text/javascript'; script.src = window.location.pathname === '/search' ? 'file1.js' : 'file2.js'; document.head.appendChild(script);
写法二(if/else清晰版)
let targetScript; if (window.location.pathname === '/search') { targetScript = 'file1.js'; } else { targetScript = 'file2.js'; } const script = document.createElement('script'); script.type = 'text/javascript'; script.src = targetScript; document.head.appendChild(script);
把这段代码放到<head>标签里,就能根据当前URL的路径,自动加载对应的脚本文件,满足你基于URL构建DOM的需求。
内容的提问来源于stack exchange,提问作者MikeL
相关产品推荐
相关产品推荐

