Jquery中的IE6和addClass()

时间:2010-01-04 20:03:21

标签: jquery css internet-explorer-6

这似乎不适用于Jquery

$(document).ready(function() {

    $(".navlist li").each(function() {
        var href = $(this).find("a").attr("href");


        if ($(this).find("a").attr("href") == window.location.pathname) {
           $(this).attr("class", "active"); 
        }
    });

});

在我的HTML中

<div id="main-navigation">
                <ul class="navlist">   
                    <li><a href="<%=ResolveUrl("~/home.aspx")%>">home</a></li>                 
                    <li><a href="<%=ResolveUrl("~/sample-templates/view-list.aspx")%>">manage sample templates</a></li>
                    <li><a href="<%=ResolveUrl("~/fractional-templates/manage.aspx")%>">manage fractional templates</a></li>
                    <li><a href="<%=ResolveUrl("~/faq.aspx")%>">faq</a></li>
                </ul>
            </div>  

在我的CSS中

.navlist li.active a
{
    color: #fff;
    background-color: #369;
    text-decoration: none;  
}

有什么建议吗?

我调试了js,问题是没有添加类

3 个答案:

答案 0 :(得分:2)

是css

应该是

.navlist .active a:link, .active a:visited, .active a:visited, .active a:hover{
    color: #fff;
    background-color: #369;
    text-decoration: none;  
}

而不是

.navlist li.active a
{
    color: #fff;
    background-color: #369;
    text-decoration: none;  
}

答案 1 :(得分:1)

第一个选择器有效吗?你试过调试吗?比如说,在alert("i am here")之前添加一些var href=...如果是,您确定比较$(this).find("a").attr("href") == window.location.pathname是真的吗?

也许您可以尝试“更智能”的jQuery选择,首先匹配具有所需网址的所有A元素,然后只需添加类名:

$(".navlist li a[href='" + window.location.pathname +"']").parent().attr("class", "active");
编辑:命名时可能存在问题。由于“class”是保留字,因此必须使用“className”属性!所以,我的代码变成了:

$(".navlist li a[href='" + window.location.pathname +"']").parent().attr("className", "active");

甚至更好:

$(".navlist li a[href='" + window.location.pathname +"']").parent().addClass("active");

答案 2 :(得分:0)

attr('href')location.pathname进行比较并不可靠。 attr()读取JavaScript属性,而不是HTML属性; href的JavaScript属性通常是已解析的绝对URI。 jQuery尝试解决这些差异的一些问题,但我不知道它总是成功的。

更可靠的是记住HTMLAnchorElement对象也可以作为Location对象使用,因此您可以直接比较它们的路径名:

if (this.hostname===location.hostname && this.pathname===location.pathname)

现在检查它是一个内部链接,其路径与当前页面相同。它会忽略任何尾随的?query#hash部分。

$(this).attr("class", "active"); 

你在标题中提到的addClass绝对是一种更好的说法。

这绝对应该适用于IE6。什么不会在IE6中工作,这可能会使你绊倒,虽然你可以拥有一个包含多个类的元素,但是你不能在同一个元素上有一个具有多个类要求的CSS选择器,例如:

a.mylink.active { ... }

这将错误地仅需要IE6中的active类。 IE6中也不支持许多其他选择器,例如>子选择器:

div.thing > a.action { ... }

在IE6中永远不会匹配。

相关问题