这是我的代码:
<script type="text/javascript">
var index = -1;
var memo = ['num1','num2','num3','num4','num5','num6'];
function start() {
index = (index + 1) % memo.length ;
var cusid_ele = document.getElementsByClassName('MemoClass');
for (var i = 0; i < cusid_ele.length; ++i) { var item = cusid_ele[i]; item.innerHTML = memo[index]; }
}
</script>
<input type="button" value="start" onclick="start()">
</br>
</br>
<span class="MemoClass"></span>
</br>
<span class="MemoClass"></span>
</br>
<span class="MemoClass"></span>
</br>
<span class="MemoClass"></span>
</br>
<span class="MemoClass"></span>
</br>
<span class="MemoClass"></span>
当您按下开始按钮时
每个类名都有一个重复值, 我希望这些值有序地给出, 这样在按START时输出: num1 num2 num3 num4 num5 num6
答案 0 :(得分:1)
因为您的索引未循环更改,所以从memo[index]
更改为memo[i];
for (var i = 0; i < cusid_ele.length; ++i) { var item = cusid_ele[i]; item.innerHTML = memo[i]; }
}
<script type="text/javascript">
var index = -1;
var memo = ['num1','num2','num3','num4','num5','num6'];
function start() {
index = (index + 1) % memo.length ;
var cusid_ele = document.getElementsByClassName('MemoClass');
for (var i = 0; i < cusid_ele.length; ++i) { var item = cusid_ele[i]; item.innerHTML = memo[i]; }
}
</script>
<input type="button" value="start" onclick="start()">
</br>
</br>
<span class="MemoClass"></span>
</br>
<span class="MemoClass"></span>
</br>
<span class="MemoClass"></span>
</br>
<span class="MemoClass"></span>
</br>
<span class="MemoClass"></span>
</br>
<span class="MemoClass"></span>
答案 1 :(得分:0)
您有错字
for (var i = 0; i < cusid_ele.length; ++i) { var item = cusid_ele[i]; item.innerHTML = memo[i]; // here change from index to i
}
一种更好的方法是将每个跨度和数组中的值一一对应,并将它们一一放置
var memo = ['num1', 'num2', 'num3', 'num4', 'num5', 'num6'];
let allspans = document.querySelectorAll('.MemoClass'); // all the spans in an array
function start() {
memo.forEach((a, post) => allspans[post].innerHTML = a) // for every value in the array, put the innerHTML of every class
}
span {
color: red;
}
<input type="button" value="start" onclick="start()">
</br>
</br>
<span class="MemoClass"></span>
</br>
<span class="MemoClass"></span>
</br>
<span class="MemoClass"></span>
</br>
<span class="MemoClass"></span>
</br>
<span class="MemoClass"></span>
</br>
<span class="MemoClass"></span>
答案 2 :(得分:0)
将备忘录[index]更改为备忘录[i],所以您拥有
for (var i = 0; i < cusid_ele.length; ++i) { var item = cusid_ele[i]; item.innerHTML = memo[i]; }