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.

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

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?

I'm using the BBQ plugin by Ben Alman

Regards, and thanks for any help that comes my way!

有帮助吗?

解决方案

window.location.hash includes the hash symbol.

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/

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/

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top