簡體   English   中英

基於html無序列表的javascript導航按鈕(上一個下一個)

[英]javascript navigation buttons (previous next) based on a html unordered list

我有一個名為index.php的頁面,其中包含這樣的div列表:

<div id="links">
     <ul>
        <li><a href="example1.php">example1</a></li>
        <li><a href="example2.php">example2</a></li>
        <li><a href="example3.php">example3</a></li>
        ......
        <li><a href="exampleN.php">exampleN</a></li>
    </ul>
</div>

那是我網站的頁面列表,顯示在index.php頁面中。 我想向站點中的每個頁面(example1,example2,example3,...,exampleN)添加一個“上一個|主頁|下一個”菜單,其中“上一個”將我帶到上一個示例,然后轉到下一個示例,例如,如果我正在觀看示例3(示例3.php頁),那么上一章將帶我進入示例2(示例2.php頁)等等。

我想使用不基於固定數組(由用戶定義)的腳本,因為我不想每次將新頁面添加到index.php列表時都更新此數組。

我想到了這樣的功能:假設我們在example2.php中

function blahblah(){
    1) get the link list using DOM from index.php (using an array)
    2) search for "example2.php" in the href value of each element in the list, to get the index of the array: in this case, "example2.php" is the 2nd link of index.php, so the array index will be 1 (i.e. alert(linkList[1].href) will print "example2.php")
    3) once we know the index, previous page index will be "index-1" and next page will be "index+1"
}

關於獲取列表(我的偽代碼中的第一點),我不知道如何使用DOM元素訪問其他頁面(在同一域中)。是否存在諸如document(“ page”)。getElementById('links')之類的東西不需要iframe?

我走對了嗎? 還是完全錯誤? 任何幫助,想法或建議,我們感激不盡。 謝謝,最好的問候

不,您無法輕松訪問其他文件,但是如果div列表在每個頁面上,則添加導航非常容易

window.onload=function() {
  var navLinks = document.getElementById("links").getElementsByTagName('a');
  var loc = location.href;
  var href,html="";
  for (var i=0;i<navLinks.length;i++) {
    href=navLinks[i].href;
    if (loc.indexOf(href)!=-1) {
      if (i==0) html+='prev ';
      else html +='<a href="'+navLinks[i-1].href'">prev</a>' 
      if (i==navLinks.length-1) html+=' next ';
      else html +='<a href="'+navLinks[i+1].href'">next</a>' 
    }
  }
  if (html) document.getElementById("links").appendChild(html);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM