1

我正在尝试制作可以突出显示当前页面的 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);

我收到 [对象] [对象] 警报。有人可以帮忙吗?

提前致谢。

4

3 回答 3

2

jQuery 方法总是返回一个 jQuery 对象。如果您想查看其中的内容,请尝试.length查看匹配的元素数量,并[0]访问各个 DOM 节点。甚至更好——console.log这样您就可以轻松检查其中的所有内容。

您的问题是虽然location.href返回整个 URL ( http://...) 并且您的链接不包含它。您可以使用location.pathname来获取路径,但突出当前页面的真正正确方法是在服务器端进行。没有理由将 JS 用于这样的事情。

于 2012-02-05T15:18:43.867 回答
0

马蒂是真的。但是您可以尝试使用 split() 方法来获取与 href 匹配的确切值。

工作示例:http: //jsfiddle.net/ylokesh/AqmHr/2/

<script>
$(document).ready(function() {

    //capture URL
    //var tempURL = window.location.href; 

    var tempURL = "http://www.websiteurl.com/index.php?pg=2"
    var urlMatch = tempURL.split('.com')[1].split('/')[1];
    var hrefVal = $("#navigation a:eq(1)").attr('href');
    $("#navigation").find("a[href='"+hrefVal+"']").html('Current Page');
});
</script>
于 2012-02-05T15:50:00.123 回答
0
//var url = 'file://one/two/three/index.php?pg=2'; // use this if testing on desktop
var url = window.location.href;
var filepath = url.lastIndexOf("/") + 1;
var matchThis = url.substr(filepath);
$('#navigation').find("a[href*='"+matchThis+"']").addClass('current');

不需要.each

信用 - https://stackoverflow.com/a/1302339/3377049

于 2018-01-18T03:43:08.840 回答