2011-06-09 38 views
0

我非常亵渎javascript。Javascript转到文档中的下一个和上一个锚点

我需要一个上一个和下一个链接,只会去上一个或下一个#anchor。

所有锚具有相同ID

的div这是我能够做到:

<script type="text/javascript"> 
$(document).ready(function() { 

// Go to the next link 
function goToNext() { 

     window.location.href = .next('#display'); 
    } 
} 

// Go to the previous link 
function goToPrev() { 

     window.location.href = .prev('#display'); 
    } 
} 

</script> 

然后

<a href="javascript:goToNext()">next</a> 
     <a href="javascript:goToPrev()" >Prev</a> 

的感谢!

+1

*“所有锚都是具有相同ID的div”*这是无效的。您不能在页面上重复使用相同的ID。 – user113716 2011-06-09 18:28:51

+1

链接锚点应始终是唯一的。你不应该给同一个锚定名称“#display”多个元素。 – Niklas 2011-06-09 18:29:02

+0

谢谢。如果我使用不同的锚名称?如何做.next和.previous? – Tiny 2011-06-09 18:38:25

回答

1

看来你正在使用jQuery。

你可以让你的ID,以结束与一个数字:

<div id="display_0">zero</div> 
<div id="display_1">one</div> 
<div id="display_2">two</div> 
<div id="display_3">three</div> 
<div id="display_4">four</div> 
<div id="display_5">five</div> 


<a href="#" id="prev">Prev</a> 
<a href="#" id="next">Next</a> 

然后绑定功能,即增加/减少索引你的nextprev链接,并设置location.hash的ID加索引。

$(document).ready(function() { 

     // index to reference the next/prev display 
    var i = 0; 
     // get the total number of display sections 
     // where the ID starts with "display_" 
    var len = $('div[id^="display_"]').length; 


     // for next, increment the index, or reset to 0, and concatenate 
     // it to "display_" and set it as the hash 
    $('#next').click(function() { 
     i = ++i % len; 
     window.location.hash = "display_" + i; 
     return false; 
    }); 


     // for prev, if the index is 0, set it to the total length, then decrement 
     // it, concatenate it to "display_" and set it as the hash 
    $('#prev').click(function() { 
     if (!i) i = len; 
     --i; 
     window.location.hash = "display_" + i; 
     return false; 
    }); 

}); 
+0

看起来不错@patrick dw!谢谢! – Tiny 2011-06-09 18:50:42

+0

@Tiny:不客气。我只是更新一些解释性评论。希望能帮助到你。 – user113716 2011-06-09 18:51:50

0

给每个人一个类,并找到他们的基础上,然后获得href属性,这应该是不同的。

document.location.hash = $("#"+document.location.hash).next(".myAnchors").attr("name"); 

<a id="number1" name="number1" href="#number1" class="myAnchors">first one</a> 
<a id="number2" name="number2" href="#number2" class="myAnchors">second one</a> 
+0

@patrcick dw这几乎是我想要的,但我认为我想要的是不可能的。 – Tiny 2011-06-09 19:37:39

相关问题