通过 .find() 和 .each() 函数获取 jQuery 当前页面
我正在尝试制作 jQuery 菜单,它可以突出显示当前页面。方法是,在选定的对象上添加current
类。
这是html:
<div class="menu_items">
<ul class="ul_items" id="navigation">
<li><a href="index.php">1</a></li>
<li><a href="index.php?pg=2">2</a></li>
<li><a href="index.php?pg=3">3</a></li>
<li><a href="index.php?pg=4">4</a></li>
<li><a href="index.php?pg=5">5</a></li>
</ul>
</div>
我尝试制作类似的东西:
$(document).ready(function(){
$("#navigation").find("a[href*='"+window.location.href+"']").each(function(){
$(this).addClass("current")
});
});
因为CSS代码很大等,完整的代码位于jsFiddle
我认为 Jquery 代码部分没有正确定义某些内容。当我尝试此操作时:
var a = $("#navigation").find("a[href*='"+window.location.href+"']");
alert(a);
我收到 [Object] [Object] 警报。有人可以帮忙吗?
提前致谢。
I'm trying to make jQuery menu, which can highlight current page. Method is, add class current
on selected.
Here is html:
<div class="menu_items">
<ul class="ul_items" id="navigation">
<li><a href="index.php">1</a></li>
<li><a href="index.php?pg=2">2</a></li>
<li><a href="index.php?pg=3">3</a></li>
<li><a href="index.php?pg=4">4</a></li>
<li><a href="index.php?pg=5">5</a></li>
</ul>
</div>
And I tried to make something like that:
$(document).ready(function(){
$("#navigation").find("a[href*='"+window.location.href+"']").each(function(){
$(this).addClass("current")
});
});
Because CSS code is large and etc, complete codes are at jsFiddle
I think that something isn't properly defined in Jquery part of code. When I try this:
var a = $("#navigation").find("a[href*='"+window.location.href+"']");
alert(a);
I get [Object] [Object] alert. Can someone help?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
jQuery 方法始终返回一个 jQuery 对象。如果您想查看其中的内容,请尝试
.length
查看匹配的元素数量,并尝试[0]
访问各个 DOM 节点。或者甚至更好 -console.log
它,这样您就可以轻松检查其中的所有内容。您的问题是,
location.href
返回整个 URL (http://...
),而您的链接不包含该内容。您可以使用 location.pathname 来获取路径,但突出显示当前页面的真正正确方法是在服务器端执行此操作。没有理由使用 JS 来做这样的事情。jQuery methods always return a jQuery object. If you want to see what's in it, try
.length
to see how many elements were matched, and[0]
to access the individual DOM nodes. Or even better -console.log
it so you can inspect everything in it easily.Your problem is though that
location.href
returns the whole URL (http://...
) and your links don't contain that. You could uselocation.pathname
to get the path, but the real correct way to highlight the current page is to do it on the server side. No reason to use JS for something like this.马蒂是真的。但您可以尝试使用 split() 方法来获取与 href 匹配的精确值。
工作示例: http://jsfiddle.net/ylokesh/AqmHr/2/
Matti is true. But what you can try is the split() method to get the exact value to match the href.
working example: http://jsfiddle.net/ylokesh/AqmHr/2/
无需
.each
积分 - https://stackoverflow.com/a/1302339/3377049
No need for
.each
credit - https://stackoverflow.com/a/1302339/3377049