如果这是一个愚蠢的问题,我很抱歉,但我正在为网站制作一些东西,无法弄清楚这个问题。
如何让这个 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>
关于javascript - 在第一次/最后一次点击时循环、显示和隐藏文本/div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52030315/