簡體   English   中英

添加側欄的可點擊按鈕或鏈接

[英]Adding clickable buttons or links for side bar

我無法在邊欄上動態添加鏈接或按鈕。 我正在嘗試使用JavaScript添加適當數量的元素或按鈕(我不知道哪個更好)。 從本質上講,這是用來制作JS問答網站的,側邊欄中的每個按鈕都會使您跳到問題(更清楚的是:問題4將您帶到第四個問題,依此類推)

這是我的側邊欄:

<div id="mySidenav" class="sidenav">
      <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>
      <a href="#">Question </a>
</div>

我的JS嘗試制作元素,但沒有這樣做:

//add question numbers to the side bar
        function questionNav(){
            for(var i = 0; i < numberOfQuestions; i++){

                    document.getElementById("mySidenav").innerHTML = "Question " + (i+1) + "<br/>";
                //var newSideBarElm = "Question " + (i+1) + "<br/>";
                //document.getElementById("mySidenav").insertAdjacentHTML = ('beforeend',newSideBarElm);    

            }
        }

我一直在嘗試許多不同的方法,但是我無法使其正常工作,如果有人能夠幫助我,我將不勝感激。

如果您想了解我如何做其他事情,這是網站的完整代碼: https : //pastebin.com/hrSADLQy

因此,假設我正確理解了您的問題,那么您當前正在做什么,將id為“ mySideNav”的div作為目標,並通過為其innerHTML屬性分配新值來覆蓋其內容。 你應該做的是

  1. 創建一個新的錨元素
  2. 使用innerHTML屬性插入所需的值(即“問題N”)
  3. 將新創建的元素追加到“ mySideNav” div元素。

我為您編寫了一個小演示 ,以查看我的答案,但還將在此答案下方發布我的代碼,以供您查看。

// Grab and Store Element to append questions to
var mySideNav = document.getElementById('mySidenav');

// Designate number of questions
var numberOfQuestions = 10;

// Loop as many times as there are questions
for (let i  = 0; i < numberOfQuestions; i++) {

   // Step 1: Create a new anchor element 
   let newQuestion = document.createElement('a');

   // Assign href to whatever you want
   newQuestion.href = '#';

   // Step 2: Use the innerHTML attribute to insert your desired value
   newQuestion.innerHTML = 'Question ' + i + '<br>';

   // Step 3: Append your newly created element to your 'mySideNav' div element.
   mySideNav.appendChild(newQuestion);

}

我希望這有幫助!

根據您的問題和您提供的代碼,我認為您需要使用onclick()屬性定義一個div才能使相應的問題可見。 可能是這樣的(假設您可以訪問此函數中的問題數量):

function questionNav(){
    for(var i = 0; i < numberOfQuestions; i++){
        document.getElementById("mySidenav").innerHTML += "<div style='cursor:pointer' onclick=navigateToQuestion(" + (i+1) + ")/> Question " + (i+1) + "</div>";
    }
}

然后定義一個onclick函數“ navigateToQuestion”以顯示作為參數傳遞的問題,可能是這樣的:

function navigateToQuestion(question){
    document.getElementById("question_" + currentQuestionInView).style.display = "none";
    currentQuestionInView = question;
    document.getElementById("question_" + question).style.display = "block";
}

還沒有測試代碼,但我認為它應該工作。 希望您能解決您的問題:)

暫無
暫無

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

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