jQuery addClass 到当前页面导航在 IE7 中不起作用
更新 感谢 @mrtsherman 验证我的代码没有问题,我深入研究了 CSS,发现没有什么特别的原因,ie7 想要在底部有一些额外的填充。这就是我讨厌ie7的原因。
我有一些非常简单的代码,自动将一个类添加到与当前页面对应的导航项。在所有浏览器(包括 ie8 和 ie9)中工作正常,但似乎在 ie7 中不起作用。谁坏了,ie7还是我?
html:
<div id="navbar">
<ul>
<li class="navitem"><a href="about.html">about us</a></li><!--navitems-->
<li class="navitem"><a href="purchase.html">purchase</a></li><!--navitems-->
<li class="navitem"><a href="sales.html">sales</a></li><!--navitems-->
<li class="navitem"><a href="contact.html">contact</a></li><!--navitems-->
</ul>
</div><!--navbar-->
js文件
$(function(){
var full_url = document.URL;
var url_array = full_url.split('/')
var $last_segment = url_array[url_array.length-1];
$('#navbar li a').each(function(){
var $href = $(this).attr('href');
if ( ($href == $last_segment) || ($href == '') ) {
$(this).addClass('curr');
} else {
$(this).removeClass('curr');
}
});
});
Update Thanks to @mrtsherman verifying my code was fine, I dove into the CSS and found that for no reason in particular, ie7 wanted a bit of extra padding on the bottom. This is why I hate ie7.
I have some pretty simple code automatically adding a class to the nav item corresponding with the current page. Works fine in all browser including ie8 and ie9 but seems to just not function in ie7. Who's broken, ie7 or me?
html:
<div id="navbar">
<ul>
<li class="navitem"><a href="about.html">about us</a></li><!--navitems-->
<li class="navitem"><a href="purchase.html">purchase</a></li><!--navitems-->
<li class="navitem"><a href="sales.html">sales</a></li><!--navitems-->
<li class="navitem"><a href="contact.html">contact</a></li><!--navitems-->
</ul>
</div><!--navbar-->
js file
$(function(){
var full_url = document.URL;
var url_array = full_url.split('/')
var $last_segment = url_array[url_array.length-1];
$('#navbar li a').each(function(){
var $href = $(this).attr('href');
if ( ($href == $last_segment) || ($href == '') ) {
$(this).addClass('curr');
} else {
$(this).removeClass('curr');
}
});
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想得越多,我就越认为问题一定与你的网址分割有关。如果尾部有斜杠,则
$last_segment
将是空字符串,因此永远不会匹配。您应该在分割之前检查并修剪它。http://jsfiddle.net/zGbJx/2/
The more I think about it, the more I think the problem must have to do with the split of your url. If there is a trailing slash then the
$last_segment
will be an empty string, thus never matching. You should check and trim that before splitting.http://jsfiddle.net/zGbJx/2/