如何根据子<a> href

时间:2015-08-18 00:02:46

标签: javascript jquery html css

I have the following markup to show a navigation menu :

<ul class="nav sf-menu">
    <li><a href="@Url.Action("Index","Home")">Home<span></span></a></li>

Now I want to add active class to the li if the current URL is equal to its <a> href.

I have tried the following:

$(function () {

    var url = window.location.pathname,
        urlRegExp = new RegExp(url.replace(/\/$/, '') + "$"); // create regexp to match current url pathname and remove trailing slash if present as it could collide with the link in navigation in case trailing slash wasn't present there
    // now grab every link from the navigation
    $('.sf-menu li').each(function () {
        // and test its normalized href against the url pathname regexp
        if (urlRegExp.test(this.href.replace(/\/$/, ''))) {
            $(this).addClass('active');
        }
    });

});

but I get an error that li does not have a href. How do I get this to work?

2 个答案:

答案 0 :(得分:3)

href属性存在于<li>元素上,而不是<a>元素上。您需要检查href的<li>,然后将该类应用于父<a>

以下是我调整代码以定位jQuery(function () { var url = window.location.pathname; if (url == '/') { jQuery('.sf-menu li > a[href="/"]').parent().addClass('active'); } else { var urlRegExp = new RegExp(url.replace(/\/$/, '') + "$"); jQuery('.sf-menu li > a').each(function () { if (urlRegExp.test(this.href.replace(/\/$/, ''))) { jQuery(this).parent().addClass('active'); } }); } }); 标记的方法:

/

<强> JSFiddle

我还检查了链接是否为jQuery(function () { var url = window.location.pathname; jQuery('.sf-menu li > a[href="' + url + '"]').parent().addClass('active'); }); ,以防止所有链接被标记为有效。

如果链接适用,您也可以尝试使用此简化版本:

SET @i := -1;

SELECT *, @i := @i + 1 AS rowNum
(
SELECT *
FROM yourTable
WHERE theField BETWEEN [begin] AND [end]
ORDER BY theField
) AS subQ
HAVING rowNum % 5 == 0
;

答案 1 :(得分:0)

试试这个

$('.sf-menu li >a').each(function () {