javascript - 单击按钮显示下一个 div
问题描述
我无法创建一个可以让我进入下一个 div 的函数。
我已经尝试了一些东西,但由于某种原因我无法让它工作
<button type="button" name="button" onclick="arrowLeft()" id="arrowLeft">Prev</button>
<button type="button" name="button" onclick="arrowRight()" id="arrowRight">Next</button>
<div class="monsterTabs" id="monsterTabs">
<div class="monsterType" id="monsterSlime" style="display:block;">
Slime
</div>
<div class="monsterType" id="monsterZombie" style="display:none;">
Zombie
</div>
<div class="monsterType" id="monsterSkeleton" style="display:none;">
Skeleton
</div>
<div class="monsterType" id="monsterWolf" style="display:none;">
Wolf
</div>
</div>
https://jsfiddle.net/gfx873ve/3
我想知道制作它的最佳方法,这样我就可以毫无问题地通过 div。
解决方案
您可以通过使用然后在调用and函数document.getElementsByClassName('monsterType');
时更新每个怪物的显示属性来获取所有怪物的集合。arrowLeft
arrowRight
我使用了一个monsterId
变量来控制当前显示的怪物。中的每个元素monsters
都将其 display 属性设置为,none
除非它是monsterId
列表中的第 -th 个元素。
该monsterId = (monsterId + monsters.length) % monsters.length;
行使用模数 (%) 运算符确保 monsterId 始终介于 0 和 monsters.length - 1 之间。
let monsters = document.getElementsByClassName('monsterType');
let monsterId = 0;
function arrowLeft() {
updateMonster(-1);
}
function arrowRight() {
updateMonster(1);
}
function updateMonster(direction) {
monsterId += direction;
monsterId = (monsterId + monsters.length) % monsters.length;
for(var i = 0; i < monsters.length; i++){
monsters[i].style.display = i === monsterId ? 'block' : 'none';
}
}
<button type="button" name="button" onclick="arrowLeft()" id="arrowLeft">Prev</button>
<button type="button" name="button" onclick="arrowRight()" id="arrowRight">Next</button>
<div class="monsterTabs" id="monsterTabs">
<div class="monsterType" id="monsterSlime" style="display:block;">
Slime
</div>
<div class="monsterType" id="monsterZombie" style="display:none;">
Zombie
</div>
<div class="monsterType" id="monsterSkeleton" style="display:none;">
Skeleton
</div>
<div class="monsterType" id="monsterWolf" style="display:none;">
Wolf
</div>
</div>
推荐阅读
- arrays - Array of strings with re
- laravel - How to start/stop specific horizon supervisor?
- sql - 组合一个 CROSS JOIN 和一个 LEFT JOIN
- r - 如何从 ggplot 中的箱线图中删除图例?
- reactjs - 如何使用 jest 和 react-testing-library 测试上下文提供的函数?
- google-cloud-firestore - 使用 angular8 在 Firestore 中使用子集合查询父集合
- javascript - 如何在值为零或以下时显示
- swift - 如何将视图控制器推送到生成的导航层次结构中
- google-sheets - 使用 Google Sheets QUERY 对不同工作表上的 weeknum = weeknum 列求和
- oracle-apex - 如何将数据从行更改为列