简体   繁体   English

哈希位置基础知识

[英]Hash location basics

I'm trying to understand how location.hash works in jQuery, for that, I'm trying to begin from the most basic form, and then once I get that right I'd go deeper, but sadly I'm already stuck at what I think should be a simple thing. 我试图理解location.hash在jQuery中是如何工作的,为此,我试图从最基本的形式开始,然后一旦我做对了,我就会更深入,但遗憾的是我已经陷入困境我认为应该是一件简单的事情。

Here's my code I created modifying someone else's code I found in a post here: 这是我创建的代码,修改了我在帖子中找到的其他人的代码:

$(document).ready(function(){

$("body").css("background-color", "#FF0");

$(window).bind( 'hashchange', function( event ) {

    if (window.location.hash == "red"){
        $("body").addClass("red");
    } else if (window.location.hash == "green") {
        $("body").addClass("green");
    }

    event.preventDefault();

});

$(window).trigger("hashchange");

}); });

And here's the page http://dlacrem.16mb.com/dlatest/hash.html 这是http://dlacrem.16mb.com/dlatest/hash.html页面

Now, as I said, I'm trying to learn so there are probably 80 mistakes in 10 lines :D but, shouldn't it be adding the red class to the body when I go to hash.html#red? 现在,正如我所说的那样,我正在努力学习,因此在10行中可能有80个错误:但是,当我去hash.html#red时,不应该将红色类添加到正文中吗?

I'm using the BBQ plugin by Ben Alman 我正在使用Ben AlmanBBQ插件

Regards, and thanks for any help that comes my way! 此致,感谢您的帮助!

window.location.hash includes the hash symbol. window.location.hash包含哈希符号。

if (window.location.hash == "#red"){
    $("body").addClass("red");
} else if (window.location.hash == "#green") {
    $("body").addClass("green");
}

Additionally, your inline-style that you set to make the body yellow will override anything you do with a class (unless you use !important, but don't do that!), so you'll want to make it yellow in the stylesheet rather than inline. 此外,您设置为使主体变为黄色的内联样式将覆盖您对类执行的任何操作(除非您使用!重要,但不要这样做!),因此您需要在样式表中将其设置为黄色而不是内联。

http://jsfiddle.net/4SwnQ/ http://jsfiddle.net/4SwnQ/

You'll note however that once you make it red, then green, it stays green. 但是你会注意到,一旦你把它变成红色,然后变成绿色,它会保持绿色。 This is because you never actually remove the classes, so it takes on the one that has the highest specificity (green in this case since it is last in the stylesheet.) To remedy this, you'll want to also remove the other class. 这是因为你从来没有真正删除过类,因此它具有最高特异性的类(在这种情况下为绿色,因为它在样式表中是最后一个。)为了解决这个问题,你还需要删除另一个类。

http://jsfiddle.net/4SwnQ/1/ http://jsfiddle.net/4SwnQ/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM