【发布时间】:2018-06-10 19:05:55
【问题描述】:
这是从this question 开始的。我打算通过回到基础来了解出了什么问题,尽管现在我遇到了这个问题。
我用数组“数字”替换了变量
var divs = document.querySelectorAll(".entry");
希望每个具有“entry”类的 div 的行为类似于前一个数组“numbers”的每个元素
但是我现在看到这个出现...
[object HTMLDivElement]
数组的元素应该在哪里。
这可能与 NodeLists 有关吗? 我试图找到解决方案,但似乎无法使其发挥作用。 当点击下一个和上一个按钮而不是上面的按钮时,如何让我的每个 div 出现?
我的完整代码如下:
<html>
<body>
<div id='entry1' class='entry'>
Left Dorchester at 11.45pm, travelling through the night. We arrived
at Liverpool dockside at
1.30pm the following day.
</div>
<div id ='entry2' class ='entry'>
Lounged about the deck most of the day, looking my last on old
England for some time, maybe.
</div>
<div class ='entry'>
Very calm sea, little breeze. We arrived at Greenock in the early
afternoon and dropped anchor.
</div>
<div id ="hello" class ='entry'>
I went on deck first thing this morning and found that we were still
lying off Greenock, but many ships
have altered their position in readiness.
</div>
<p id="filler"></p>
<button id="back">PREVIOUS</button>
<button id="forward">NEXT</button>
<script>
var divs = document.querySelectorAll(".entry");
var i=-1;
var text = "";
document.getElementById("back").addEventListener("click", function
previous() {
if (i > 0) {
text = divs[--i];
}
document.getElementById("filler").innerHTML = text;
});
document.getElementById("forward").addEventListener("click", function
next(){
if (i < divs.length - 1) {
text = divs[++i];
}
document.getElementById("filler").innerHTML = text;
});
</script>
</body>
</html>
【问题讨论】:
标签: javascript loops iteration nodes