这是继this question在这里。我打算通过回归基础来理解出了什么问题,尽管现在我遇到了这个问题。
我将数组'numbers'替换为变量
var divs = document.querySelectorAll(".entry");
希望使每个带有“入口”类的div都像上一个数组“数字”的每个元素一样
但是我现在看到这个......
[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>
当您选择返回的对象是NodeList的元素并访问nodeList Content或text中的节点时,请使用textContent或innerHTML查看下面的示例以了解问题
var divs = document.querySelectorAll(".entry");
var i=-1;
var text = "";
document.getElementById("back").addEventListener("click", function
previous() {
if (i > 0) {
text = divs[--i].textContent ;
}
document.getElementById("filler").innerHTML = text;
});
document.getElementById("forward").addEventListener("click", function
next(){
if (i < divs.length - 1) {
text = divs[++i].textContent ;
}
document.getElementById("filler").innerHTML = text;
});
<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>
</body>
</html>