这是从this question开始的。我打算通过回归基础来理解出了什么问题,尽管现在我遇到了这个问题。
我将数组'numbers'替换为变量
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>
答案 0 :(得分:1)
将您的document.getElementById("filler").innerHTML = text;
更改为
document.getElementById("filler").innerHTML = text.innerHTML;
。
或者您可以使用div
的{{3}}属性而不是innerText
。
答案 1 :(得分:0)
当您选择元素时,返回的对象是NodeList并访问nodeList内容或文本中的节点,使用 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;
});
&#13;
<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>
&#13;