如何使用jQuery的top.location.pathname匹配多个路径?
嘿,别担心,这个问题一点都不简单——很多自学前端的朋友都会在这里卡壳,我来一步步帮你搞定!
匹配多个特定路径运行jQuery函数
首先,我们可以把需要触发函数的所有路径放进一个数组,然后检查当前页面的路径是否在这个数组里就行。举个直观的例子:
// 把你需要触发函数的路径都列在这里 const targetPaths = ['/', '/index.html', '/home']; // 获取当前页面的路径(比如打开首页时,这个值就是"/") const currentPath = window.location.pathname; // 检查当前路径是否在目标列表里 if (targetPaths.includes(currentPath)) { // 这里写你要运行的jQuery逻辑 $(document).ready(function() { console.log("当前在目标路径上,执行函数!"); // 你的业务代码,比如修改DOM、绑定事件之类的... }); }
如果怕路径有大小写问题(比如服务器返回/Index.html)或者多余的斜杠(比如//home),可以先做个标准化处理:
// 把当前路径转成小写,去掉首尾的斜杠 const normalizedCurrentPath = currentPath.trim().toLowerCase().replace(/^\/+|\/+$/g, ''); // 把目标路径也做同样的标准化 const normalizedTargets = targetPaths.map(path => path.trim().toLowerCase().replace(/^\/+|\/+$/g, '')); // 再判断是否匹配 if (normalizedTargets.includes(normalizedCurrentPath)) { // 执行你的jQuery函数 }
相反逻辑:不在目标路径时运行函数
如果想要在除了这些特定路径之外的页面运行函数,只需要把判断条件取反就行——也就是在includes前面加个!:
const targetPaths = ['/', '/index.html', '/home']; const currentPath = window.location.pathname; if (!targetPaths.includes(currentPath)) { $(document).ready(function() { console.log("当前不在目标路径上,执行函数!"); // 你的业务逻辑代码... }); }
进阶:用正则匹配更灵活的路径
如果你的路径规则更复杂(比如要匹配所有以/blog开头的页面),可以用正则表达式来实现:
// 匹配根路径、首页,以及所有/blog开头的路径 const pathRegex = /^(\/|\/index\.html|\/blog\/.*)$/; const currentPath = window.location.pathname; // 匹配时执行 if (pathRegex.test(currentPath)) { $(document).ready(function() { // 你的代码 }); } // 相反逻辑:不匹配时执行 if (!pathRegex.test(currentPath)) { $(document).ready(function() { // 你的代码 }); }
这样应该就能完美解决你的需求啦!如果还有细节需要调整,随时再琢磨~
内容的提问来源于stack exchange,提问作者Julian Tennyson
相关产品推荐
相关产品推荐

