jQuery当前页面通过.find()和.each()函数 [英] jQuery current page via .find() and .each() function
问题描述
我试图制作jQuery菜单,它可以突出显示当前页面。方法是,在所选内容上添加class current
。
这里是html:
< div class =menu_items >
< ul class =ul_itemsid =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 + ']);
警报(a);
我得到[Object] [Object] alert。有人可以帮忙吗?
预先感谢。
解决方案 .length
以查看匹配的元素数量,以及 [0]
访问单个DOM节点。或甚至更好 - console.log
它可以让你轻松检查所有内容。
你的问题在于 location.href
会返回整个网址( http:// ...
),您的链接不包含。您可以使用 location.pathname
来获取路径,但突出显示当前页面的真正正确方法是在服务器端执行。没有理由使用JS这样的东西。
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.
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 use location.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.
这篇关于jQuery当前页面通过.find()和.each()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!