我有以下 html 菜单:
<ul>
<li><a href="About/about-page.html"></a></li>
<li><a href="Services/services-page.html"></a></li>
</ul>
如何使用 jQuery 检查当前 URL 中是否包含例如 'About/' 的字符串(如 'about' 任何情况 + '/' )?
其中“关于/”可以是任何单词。
基本上运行我的菜单并检查是否有与 URL 部分相同的字符串。 例如:
- www.website.com/about/= true
- www.website.com/about/something.html = true
- www.website.com/about-something.html = false
- www.website.com/services/about.html = false
非常感谢任何帮助。
最佳答案
假设变量 currentURL
包含您要检查的字符串,并且您不关心它是否有大写“A”:
if(currentURL.toLowerCase().indexOf("about") != -1) {
//Contains 'about'
}
如果你想使用当前页面的URL:
var currentURL = window.location.href;
根据您的评论,我认为您正在尝试将类应用于列表中 href
属性中包含“about”一词的任何 a
元素。在这种情况下:
$("li > a").filter(function() {
if($(this).attr("href").toLowerCase().indexOf("about") != -1) return true;
return false;
}).addClass("newClass");
更新(根据您的评论)
您可以将其包装在一个函数中,该函数采用要查找的关键字和要添加的类的名称,然后在必要时调用它:
function applyClass(keyword, class) {
$("li > a").filter(function() {
if($(this).attr("href").toLowerCase().indexOf(keyword) != -1) return true;
return false;
}).addClass(class);
}
applyClass('service', 'newClass'); //Or for example applyClass('about', 'newClass');
关于jquery - URL - 查看 URL 中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6597558/