最好的方法是(a)使用“下一个/上一个”按钮浏览选择菜单的选项,而(b)还在下方显示每个选择选项的唯一内容?
如果有帮助,我基本上是在尝试将这两个代码元素组合为一个:
由于某种原因,在菜单内选择一个选项后,它中断了上一个/下一个按钮的循环。它被前两个选项卡住并来回跳动。我意识到这个问题存在于我的jQuery脚本中-它已损坏并且有些多余。我缺少引起问题的原因吗?
cycleMenu('#upcomingEventsMenu');
function cycleMenu(cycleMenuID) {
$(cycleMenuID).on('change', function() {
$('.menu__content').hide();
$('#' + $(cycleMenuID).val()).show();
$(cycleMenuID + ' option').removeAttr('selected');
$(cycleMenuID + ' option:selected').attr('selected', 'selected');
if ($(cycleMenuID + ' option:first').is(":selected")) {
$(cycleMenuID + ' option:selected').attr('selected', 'selected');
} else {
$(cycleMenuID + ' option:first').removeAttr('selected');
}
})
$('#next').on('click', function() {
if ($(cycleMenuID + ' option:first').is(":selected")) {
$(cycleMenuID + ' option:selected').attr('selected', 'selected');
} else {
$(cycleMenuID + ' option:first').removeAttr('selected');
}
$(cycleMenuID + ' option:selected').removeAttr('selected').next('option').attr('selected', 'selected');
$('.menu__content').hide();
$('#' + $(cycleMenuID).val()).show();
})
$('#prev').on('click', function() {
var isFirstElementSelected = $(cycleMenuID + ' option:selected').index() == 0;
if (!isFirstElementSelected) {
$(cycleMenuID + ' option:selected').removeAttr('selected').prev('option').attr('selected', 'selected');
} else {
$(cycleMenuID + ' option:selected').removeAttr('selected');
$(cycleMenuID + ' option').last().attr('selected', 'selected');
}
$('.menu__content').hide();
$('#' + $(cycleMenuID).val()).show();
})
}
.menu__content {
display: none;
}
.menu__content:first-of-type {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="menu">
<header class="menu__header">
<button type="button" id="prev">Previous</button>
<select class="menu__select" id="upcomingEventsMenu">
<option value="w-0065">Window: 0065</option>
<option value="w-0066">Window: 0066</option>
<option value="w-0067">Window: 0067</option>
</select>
<button type="button" id="next">Next</button>
</header>
<div class="menu__body">
<div class="menu__content" id="w-0065">
<p>Window: 0065 CONTENT</p>
</div>
<div class="menu__content" id="w-0066">
<p>Window: 0066 CONTENT</p>
</div>
<div class="menu__content" id="w-0067">
<p>Window: 0067 CONTENT</p>
</div>
</div>
</div>