【问题标题】:Jquery addClass when page loads specific URL页面加载特定URL时的Jquery addClass
【发布时间】:2018-12-28 06:18:09
【问题描述】:

我只在页面加载特定 URL (example.com/#test) 但似乎无法获取时才尝试添加一个类。

$(document).ready(function() {
  if(window.location.href === "https://example.com/#test"){
    $('.test').addClass('display');
  } else {
    $('.test').removeClass('display');
  }
});

【问题讨论】:

    标签: jquery url hash


    【解决方案1】:

    window.location 对象有一个hash 成员,其中包含# 标记上的所有字符。
    试试:window.location.hash.indexOf("test") > -1 作为你的条件。

    例如:

    $(document).ready(function() {
        if(window.location.hash.indexOf("test") > -1){
            $('.test').addClass('display');
        } else {
            $('.test').removeClass('display');
        }
    });
    

    【讨论】:

    • 当页面加载时,什么也没有发生。但是如果我添加带有“#test”的链接作为href,然后加载没有哈希的页面(example.com)。单击该链接,然后将“tabindex =”-1“添加到 div。类中没有添加任何内容。现在,如果我使用该哈希 (example.com/#test) 加载页面,则类和"tabindex="-1" 也不存在。
    • 将 "$(document).ready(function()" 更改为 "jQuery(document).ready(function($)" 并且可以正常工作。谢谢
    • 我明白了,您必须使用 WordPress 或具有与 $ 功能类似的限制。
    猜你喜欢
    • 1970-01-01
    • 2022-11-18
    • 2015-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-17
    相关资源
    最近更新 更多