簡體   English   中英

循環單擊,在第一次/最終單擊時顯示和隱藏文本/ div

[英]Cycle through, Show and Hide Text/div on first/last click

抱歉,這是一個愚蠢的問題,但是我正在為某個網站制作商品,無法解決這個問題。

如何使該div在第一次單擊按鈕時出現,在數組中循環,然后在數組中的最后一項之后消失?

 var myArray = ["Hello", "Thank you", "Goodbye"]; var myIndex = 1; var print = document.getElementById('print'); print.innerHTML = myArray[0]; //Print first value of array right away. function nextElement() { print.innerHTML = myArray[myIndex++ % myArray.length]; }; 
 #notfound { background: #2abfffff; padding: 19px; margin: 15px; color: #fff; } 
 <div id="notfound"> <p><span id="print"></span>.</p> </div> <a id="click" href="#" onclick="nextElement();">Click</a> 

JSfiddle: http : //jsfiddle.net/jBJ3B/382/

因為您不希望div在第一次單擊之前出現,所以請立即刪除帶有//Print first value of array right away.

一種選擇是從索引-1開始,在索引為0時使元素可見,在索引大於或等於數組的長度時隱藏元素:

 var arr = ["Hello", "Thank you", "Goodbye"]; var index = -1; var print = document.getElementById('print'); function nextElement() { index++; if (index >= arr.length) { print.style.visibility = 'hidden'; return; } if (index === 0) print.style.visibility = 'visible'; print.textContent = arr[index]; } 
 #notfound { background: #2abfffff; padding: 19px; margin: 15px; color: #fff; } .print { visibility: hidden; } 
 <div id="notfound"> <p><span id="print"></span>.</p> </div> <a id="click" href="#" onclick="nextElement();">Click</a> 

如果您需要在再次點擊時重新出現該元素,請使用模將最后的index設置為-1

 var arr = ["Hello", "Thank you", "Goodbye"]; var index = -1; var print = document.getElementById('print'); function nextElement() { index++; if (index >= arr.length) { print.style.visibility = 'hidden'; index = -1; return; } if (index === 0) print.style.visibility = 'visible'; print.textContent = arr[index]; } 
 #notfound { background: #2abfffff; padding: 19px; margin: 15px; color: #fff; } .print { visibility: hidden; } 
 <div id="notfound"> <p><span id="print"></span>.</p> </div> <a id="click" href="#" onclick="nextElement();">Click</a> 

您可以在nextElement()內部檢查該元素是否為最后一個元素,然后隱藏div。

   function nextElement() {
      print.innerHTML = myArray[myIndex++%myArray.length];
      if(myIndex>myArray.length){
        document.getElementById("notfound").style.visibility = "hidden";
      }
   };

JSFiddle: http : //jsfiddle.net/jBJ3B/384/

是您要嘗試做的事情: http : //jsfiddle.net/yvbenitah/jBJ3B/393/

如果是,則僅添加該行:

document.getElementById('notfound').style.display = 'none';

暫無
暫無

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

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