我想对具有相同类的多个选择应用更改功能。我想要的是当您选择一个与data-tab具有相同值的选项时,要显示该选项卡的内容。还可以默认选择值为0的第一个选项吗?我的代码工作正常,但仅适用于第一批选择。这是我到目前为止的内容: https://codepen.io/tonyart/pen/VwwBzbP
<script>
$('.tab-content').hide();
$('#select-box').change(function () {
var tab = $(this).children("option:selected").val();
$(".tab-content").removeClass("selected").hide();
$('.tab-content[data-tab=' + tab + ']').addClass("selected").show();
});
</script>
<select id="select-box">
<option>select year</option>
<option value="0">2018</option>
<option value="1">2017</option>
</select>
<div id="" class="tab-content" data-tab="0">
content 2018 first
</div>
<div id="" class="tab-content" data-tab="1">
content 2017 first
</div>
<select id="select-box">
<option>select year</option>
<option value="2">2018</option>
<option value="3">2017</option>
</select>
<div id="" class="tab-content" data-tab="2">
content 2018 second
</div>
<div id="" class="tab-content" data-tab="3">
content 2017 second
</div>
答案 0 :(得分:0)
您不能有多个具有相同Id
的元素,一个ID必须是唯一的。
所以我将<select id="select-box">
更改为<select class="select-box">
您可以使用以下代码:
$('.tab-content').hide();
$('.select-box').change(function() {
var tab = $(this).children("option:selected").val();
$(this).nextAll(".tab-content").removeClass("selected").hide();
$(this).nextAll('.tab-content[data-tab=' + tab + ']').addClass("selected").show();
});
演示
$('.tab-content').hide();
$('.select-box').change(function() {
var tab = $(this).children("option:selected").val();
if ($.isNumeric(tab)) {
$(this).nextAll(".tab-content").removeClass("selected").hide();
$(this).nextAll('.tab-content[data-tab=' + tab + ']').addClass("selected").show();
}
});
$('.select-box').trigger("change")
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="select-box">
<option>select year</option>
<option value="0" selected>2018</option>
<option value="1">2017</option>
</select>
<div id="" class="tab-content" data-tab="0">
content 2018 first
</div>
<div id="" class="tab-content" data-tab="1">
content 2017 first
</div>
<select class="select-box">
<option>select year</option>
<option value="2">2018</option>
<option value="3">2017</option>
</select>
<div id="" class="tab-content" data-tab="2">
content 2018 second
</div>
<div id="" class="tab-content" data-tab="3">
content 2017 second
</div>