简体   繁体   中英

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.location.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
});

试一试

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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