【问题标题】:Jquery: conditionally add class if the url contains a specific hash valueJquery:如果url包含特定的哈希值,则有条件地添加类
【发布时间】:2011-10-20 11:30:29
【问题描述】:

我怎样才能添加一个类似的条件语句

if(window.location.href.indexOf("#/brandpartners"))
    {
    $("#brandpartners").addClass("specialbrand");
    }

哈希似乎破坏了陈述。有没有更好的办法?

【问题讨论】:

  • “哈希”是什么意思?

标签: jquery hash conditional


【解决方案1】:

indexOf() 如果未找到字符串,则返回 -1,其评估结果为“真实”,因此您的 if 语句没有按照您的想法执行。所以试试:

if (window.location.href.indexOf("#/brandpartners") != -1) {}

【讨论】:

    【解决方案2】:

    首先,你不能那样使用 indexOf 。它返回-1,当它没有找到不是假的时候。

    对我来说,仅使用位置对象中哈希值的内置解析更有意义。我建议这样做:

    if (window.location.hash == "#brandpartners") {
        $("#brandpartners").addClass("specialbrand");
    }
    

    我不知道您的 URL 结构,但对于简单的哈希值,# 之后不需要斜杠。但是,如果你坚持使用斜线,它会是这样的:

    if (window.location.hash == "#/brandpartners") {
        $("#brandpartners").addClass("specialbrand");
    }
    

    【讨论】:

    • 他可能正在使用哈希,因为他正在通过 xhr 请求从 /brandpartners 页面加载页面内容。你剩下的答案是正确的。
    【解决方案3】:

    正如@jfriend00所说,应该是:

    if(window.location.href.indexOf("#/brandpartners")!=-1)
                {
    $("#brandpartners").addClass("specialbrand");
                }
    

    【讨论】:

      【解决方案4】:

      哈希 (#) 对我来说根本没有破坏声明。但我不知道你为什么在不需要 / 的时候在里面。

      var str = "http://stackoverflow.com/questions/6950161#hmenus";
      alert(str.indexOf("#hmenus"));
      

      此代码警告 42,这意味着它应该做你想做的事。我

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-06-08
        • 1970-01-01
        • 2013-03-30
        • 2011-12-13
        • 1970-01-01
        • 1970-01-01
        • 2014-01-09
        • 2013-04-29
        相关资源
        最近更新 更多