Javascript 获取锚点/散列的索引

Javascript 获取锚点/散列的索引,javascript,jquery,hash,indexing,Javascript,Jquery,Hash,Indexing,我在这里自杀 当我输入index.html#about(或者喜欢它并打开它)时,我想得到它的index(),并将它作为“slideNumber”插入下面的脚本中 加价 <div id="slideshow"> <div id="frontpage"> <div id="About"> <div id="Contact"> </div> #about是2,而#contact是3,依此类推 我该怎么做 slides

我在这里自杀

当我输入index.html#about(或者喜欢它并打开它)时,我想得到它的index(),并将它作为“slideNumber”插入下面的脚本中

加价

<div id="slideshow">
    <div id="frontpage">
    <div id="About">
    <div id="Contact">
</div>
#about是2,而#contact是3,依此类推

我该怎么做

slides = {frontpage: 1, about: 2, contact: 3};
$('.slideshow').cycle(slides[hash]);
我想,要让它充满活力,你可以使用这样的东西:

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


类似这样的简单操作应该可以在页面加载时使用:

if(window.location.hash != undefined) {
  var slideNumber = $(window.location.hash).index() + 1;
}
如果在页面中导航,可以在页面内部执行绑定和index()调用,以便在哈希更改时更新:

$(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

在选择器中,您确定要使用“.slideshow”来选择元素w/class=“slideshow”还是要使用“#slideshow”来获取id=“slideshow”…?您看过jQuery.index()函数了吗?@Kchau:Yes@Pointy:Yes,这就是我想要使用的。但我似乎无法让它发挥作用。我想我错过了一些基本的东西。如何获取“window.location.hash.slice(1)”的索引()??这就是我想让它变得动态的原因,所以我不需要写页面标题。如何获取以下内容的索引():window.location.hash.slice(1)???警报(window.location.hash.slice(1.index());不起作用…如果你输入index.html#contact??,我想激活它怎么办???您的解决方案不会这样做,只有当您在要开始的页面上时才会这样做。如果您使用jQuery,我的第一个代码段可能会被抛出到.ready()块中,以便在页面加载时,它会运行该代码段并为您提供slideNumber。
$(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