2011-02-15 169 views
0

我在這裏殺了我的自我。獲取錨索引/散列

當我的index.html#約鍵入(或喜愛它,打開它)我想這個索引(),並在下面的腳本「slideNumber」插入。

標記

<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」 將是2,且 「#contact」 將是3等。

我如何做到這一點?

+0

在你的選擇,你確定要使用'.slideshow'選擇元素w/class =「slideshow」,或者你想用'#slideshow'來獲得id =「slideshow」...? – kafuchau 2011-02-15 13:51:03

+0

你看過jQuery的「.index()」函數嗎? – Pointy 2011-02-15 13:55:23

+0

@Kchau:是 @Pointy:是的,這就是我想要使用的。但我似乎無法讓它工作。我想我錯過了某些東西。我怎樣才能得到的索引():「window.location.hash.slice(1)」??這就是我想要的 – 2011-02-15 13:58:48

回答

1

一些簡單的像這應該在頁面加載工作:

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

如果你導航THROU GH的頁面,你可以做你的綁定,做索引()調用內部,這樣當哈希值發生變化,它會更新:

$(window).bind('hashchange', function() { //detect hash change 
    var slideNumber = $(window.location.hash).index(); //slideNumber 
    $('.slideshow').cycle(slideNumber); //Slideshow-number 
}); 
0
slides = {frontpage: 1, about: 2, contact: 3}; 
$('.slideshow').cycle(slides[hash]); 

爲了使動態,你可以使用這樣的事情,我想:

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

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

試試這個

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