我有两个按钮,当我点击其中一个时,函数会添加"选定"的类,但如果我按下另一个按钮,这两个按钮会保持同一个类,我使用了兄弟选择器,但工作不正常,你能帮我吗?
$('.btn-switch-view').on('click', function() {
$(this).addClass('btn-switch-view-selected');
$('.btn-group').siblings('a.btn-switch-view-selected').removeClass('btn-switch-view-selected');
});
.btn-group .btn-default.btn-switch-view {
color: #b2b2b2;
}
.btn-group a.btn-default.btn-switch-view:hover,
a.btn-default.btn-switch-view-selected {
color: #1b4298!important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="btn-group">
<a href="#" id="grid" class="btn btn-default btn-sm btn-switch-view">
<i class="fa fa-th-large" aria-hidden="true"></i>
</a>
<a href="#" id="list" class="btn btn-default btn-sm btn-switch-view">
<i class="fa fa-th-list" aria-hidden="true"></i>
</a>
</div>
您已经在this
中有了锚点,现在以同级锚点为目标,并删除类
$('.btn-switch-view').on('click', function() {
$(this).addClass('btn-switch-view-selected')
.siblings()
.removeClass('btn-switch-view-selected');
});
.btn-group .btn-default.btn-switch-view {
color: #b2b2b2;
}
.btn-group a.btn-default.btn-switch-view:hover,
a.btn-default.btn-switch-view-selected {
color: #1b4298!important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="btn-group">
<a href="#" id="grid" class="btn btn-default btn-sm btn-switch-view">
<i class="fa fa-th-large" aria-hidden="true">Button</i>
</a>
<a href="#" id="list" class="btn btn-default btn-sm btn-switch-view">
<i class="fa fa-th-list" aria-hidden="true">Button</i>
</a>
</div>
$('.btn-group').siblings('a.btn-switch-view-selected')
应该是
$(this).siblings('a.btn-switch-view-selected')
因为您试图将目标锁定在.btn-switch-view
(单击的元素(的同级,而不是.btn-group