我有一个包含多个 div 的页面。我希望有一些按钮,当单击时,可以转到下一个 div。例如。 Div #1 在页面上可见。它上面有一个“下一步”按钮。当用户单击下一个按钮时,它会转到同一页面上先前隐藏/不可见(设置为显示:无)的另一个 div。 这是我正在编辑的网页。如果可能的话,我愿意使用非 JS 解决方案,但我认为 JS 是解决这个问题的最佳/最有效的方法?
我在想类似this的东西,但是复制它不起作用,而且无论我修改了多少代码,我尝试过的其他任何事情都不起作用。
我对 javascript 还不太了解,所以在掌握必要的知识之前就尝试这个是我的错,但我非常想让它工作哈哈
这是我尝试用代码做的事情的高度简化版本:
CSS:
.entry {
text-align: left;
padding-top: 0px;
padding-bottom: 1px;
padding-left: 10px;
padding-right: 10px;
font-size: 15px;
font-family: Book Antiqua;
width: 550px;
height:500px;
overflow:auto;
margin: auto;
}
HTML:
<div class="entry">
<p>paragraph text 1</p>
<button class="next">Next</button>
</div>
<div class="entry" style="display:none;">
<p>paragraph text 2</p>
<button class="back">Back</button>
<button class="next">Next</button>
</div>
<div class="entry" style="display:none;">
<p>paragraph text 3</p>
<button class="back">Back</button>
<button class="next">Next</button>
</div>
Javascript:
$('.next').click(function(){
$(this).parent().hide().next().show();//hide parent and show next
});
$('.back').click(function(){
$(this).parent().hide().prev().show();//hide parent and show previous
});
我认为问题与缺少父元素有关?但我不确定。
您的代码似乎可以工作,但它有点脆弱,因为它依赖于非常特定的 HTML 结构。这是您的代码的作用
$(this)
- 选择刚刚单击的按钮.parent()
选择按钮的父元素,应该是 .entry
元素.hide()
- 这将隐藏刚刚选择的 .entry
元素.next()
- 这将选择刚刚选择的 .entry
元素之后出现的元素。希望这将是另一个.entry
元素。.show()
- 这将显示现在选择的任何元素相反,我建议做这样的事情。首先,我们选择所有
.entry
元素一次,并跟踪当前显示的元素的索引。
单击按钮时,我们可以使该数字向上或向下,然后显示具有匹配索引的
.entry
。这不再要求 HTML 具有极其特定的格式和顺序。
const entryElements = $('.entry');
let entryIndex = 0;
$('.next').click(function(){
entryIndex++;
entryElements.hide();
$(entryElements[entryIndex]).show();
});
$('.back').click(function(){
entryIndex--;
entryElements.hide();
$(entryElements[entryIndex]).show();
});
.entry {
text-align: left;
padding-top: 0px;
padding-bottom: 1px;
padding-left: 10px;
padding-right: 10px;
font-size: 15px;
font-family: Book Antiqua;
width: 550px;
height:500px;
overflow:auto;
margin: auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="entry">
<p>paragraph text 1</p>
<button class="next">Next</button>
</div>
<div class="entry" style="display:none;">
<p>paragraph text 2</p>
<button class="back">Back</button>
<button class="next">Next</button>
</div>
<div class="entry" style="display:none;">
<p>paragraph text 3</p>
<button class="back">Back</button>
</div>