我对jquery很新。如何使用data
属性进行切换?
我想选择具有class="filter-group"
的元素和与按钮相同的data-toggle
属性:
$('button').click(function() {
var toggleID = $(this).data('toggle');
$('.filter-group[data-toggle= toggleID ]').toggle();
});
答案 0 :(得分:0)
您的问题在这一行:
$('.filter-group[data-toggle= toggleID ]').toggle();
将其更改为:
$('.filter-group[data-toggle=' + toggleID + ']').toggle();
$(".filter-group").hide();
$('button').click(function() {
var toggleID = $(this).data('toggle');
$('.filter-group[data-toggle=' + toggleID + ']').toggle();
});

* {
margin:0;
padding:0;
box-sizing:border-box;
font-size:1.3rem;
}
button {
padding:1rem;
background-color:salmon;
border:none;
}
.filter-group {
background-color:silver;
padding:1rem;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" data-toggle="toggle1">Button 1</button>
<button type="button" data-toggle="toggle2">Button 2</button>
<div class="filter-group" data-toggle="toggle1">
Filter Group 1
</div>
<div class="filter-group" data-toggle="toggle2">
Filter Group 2
</div>
&#13;
答案 1 :(得分:0)
您也可以这样做。根据按钮attr
定义类名<button type="button" data-toggle="toggle1">Button 1</button>
<button type="button" data-toggle="toggle2">Button 2</button>
<div class="filter-group toggle1" data-toggle="toggle1">
Filter Group 1
</div>
<div class="filter-group toggle2" data-toggle="toggle2">
Filter Group 2
</div>
以这种方式更改你的js。
$(".filter-group").hide();
$('button').click(function() {
var toggleID = $(this).attr('data-toggle');
$("."+toggleID).toggle();
});