比较 URL 字符串和菜单字符串,然后使用 jQuery 添加类
compare url string and menu string then add class using jquery
我有一个看起来像这样的URL:
http://www.website.co.uk/en-us/aboutus/thegroup/test.aspx
我的页面上有一个 UL LI 菜单:
<ul>
<li><a href="/aboutus/thegroup/test.aspx">Test</a></li>
<li>Hello</li>
<li>Bye</li>
<li>Something</li>
<li>Cars</li>
</ul>
我在每个页面上都有菜单,并希望使用 jquery 检查该页面上的 im。如果我是,那么将A/li加粗,以便用户知道他们在页面上。
我尝试了以下方法:
$(document).ready(function () {
if(window.location.href.indexOf("test")) //
{
alert("your url contains the name test");
}
});
但是 id 就像不涉及硬编码 URL 字符串的值的东西。好像用户决定向 UL/LI 添加更多链接一样,jquery 需要自动检查链接和 url 并向 LI 添加一个类(以便我可以设置它的样式)。
希望这是足够的信息。
问题是因为 indexOf()
方法在找不到值时返回-1
。您需要检查该值,而不是像当前那样将结果强制转换为布尔值。试试这个:
$(document).ready(function () {
var loc = window.location.href;
$("ul a").each(function() {
if (loc.indexOf($(this).attr("href")) != -1) {
$(this).addClass("current");
}
});
});
您需要使选择器更具体一些,例如#menu a
这个?
$('ul#menu a').each(function() {
if(window.location.href.indexOf($(this).attr('href')) !== -1) {
$(this).closest('li').addClass('yourClass');
}
});
我在您的ul
中添加了一个 id menu
,以基本上将您的菜单栏与可能在同一页面中的其他ul
区分开来。 如果找不到在参数中搜索的字符串,则!== -1
indexOf
返回 -1。
如果不包含字符串,indexOf
返回 -1:
(document).ready(function () {
if(window.location.href.indexOf("test") != -1) //
{
alert("your url contains the name test");
}
});
$(document).ready(function () {
var liTest = $('ul > li'); // ' was missing
liTest.each(function() {
if(window.location.href == $('a', this).attr('href')) //
{
$(this).css('font-weight', 'bold');
return;
}
});
});
相关文章:
- 字符串Jquery结构中的变量
- 在字符串 jquery 中添加空格
- 如何在字符串 jQuery 上调用函数
- 将 .val() 转换为字符串 jQuery
- 如何放置 PHP 字符串 jQuery 验证错误消息
- 查找字符串 jQuery/Javascript 的部分
- 从字符串 jQuery 中删除字符串
- 比较明显相等的字符串 JQuery
- 在字符串中使用 PHP 作为字符串.(JQuery)
- 比较两个字符串(jquery .text() 和文字字符串)
- 替换<a>如果它以字符串JQuery结尾
- 字符串jQuery剩余的空白数量
- 重新注册字符串jquery.Ui可拖动
- 字符串替换为另一个字符串jquery/javascript
- 如果子值与某个字符串JQuery匹配,则隐藏父元素
- 单击时从输入中删除字符串?jQuery
- 如何获取特定子字符串jquery之后的字符串
- 不能识别父-字符串JQuery中的子字符串
- 翻译KeyDown键码字符串(jQuery)
- 即使我没有引号来转义,它仍然说我有一个未闭字符串(Jquery)