开发者

Get index of anchor/hash

I'm killing my self here.

When I type in index.html#about (or favorite it and open it) i want to get the index() of this, and insert it in the below script as "slideNumber".

Markup

<div id="slideshow">
    <div id="frontpage">
    <div id="About">
    <div id="Contact">
</div>

jQuery

$(window).bind('hashchange', function () { //detect hash change
    var hash = window.loc开发者_StackOverflow社区ation.hash.slice(1); //hash to string (= "myanchor")
    $('.slideshow').cycle(slideNumber); //Slideshow-number
});

"#about" would be 2 and "#contact" would be 3 and so on.

How do I do this??


Something simple like this should work on the page load:

if(window.location.hash != undefined) {
  var slideNumber = $(window.location.hash).index() + 1;
}

If you're navigating through the page, you can do your bind and do the index() call inside so that when the hash changes, it'll update:

$(window).bind('hashchange', function () { //detect hash change
    var slideNumber = $(window.location.hash).index(); //slideNumber
    $('.slideshow').cycle(slideNumber); //Slideshow-number
});


Give this a try

var slideNumber = $("div#" + window.location.hash.slice(1)).prevAll().length


slides = {frontpage: 1, about: 2, contact: 3};
$('.slideshow').cycle(slides[hash]);

To make it dynamic you could use something like this, I guess:

$('#slideshow>div').each(function(i) {
  if(this.id == hash) {
    $('.slideshow').cycle(i);
  }
}

or

$('.slideshow').cycle($('#slideshow>div').index(hash) + 1);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜