gpt4 book ai didi

javascript - 如果其他按钮具有特定类别,则切换按钮

转载 作者:行者123 更新时间:2023-12-01 00:49:28 25 4
gpt4 key购买 nike

如果 1 个或多个其他按钮具有类 .selected,我会尝试禁用/启用(切换)按钮

我已经尝试过此操作,但仅在选择一个按钮时才有效

$('body').on("click", "button.item-select", function (e) {
e.preventDefault();
let maxItems = 2;
let Items = $('button.item-select.selected').length;

if(Items < maxItems) {
$(this).toggleClass('select');
$(this).toggleClass('selected');
} else {
$(this).addClass('select');
$(this).removeClass('selected');
}

if($(this).hasClass('selected')) {
$('.change-this').prop("disabled", false);
} else {
$('.change-this').prop("disabled", true);
}
});
.row {
background: #f8f9fa;
margin-top: 20px;
}

.col {
border: solid 1px #6c757d;
padding: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>

<button type="button" class="btn btn-danger change-this" disabled>Disabled/enabled</button>

<button type="button" class="btn btn-primary item-select">First</button>
<button type="button" class="btn btn-primary item-select">Second</button>
<button type="button" class="btn btn-primary item-select">Third</button>

有没有办法仅当其中一个按钮具有 .selected 类时启用该按钮,否则保持禁用状态?

jsfiddle:https://jsfiddle.net/f56mzkae/

最佳答案

因此,根据您对评论的解释:

当单击按钮时,我会切换该按钮上的 .selected 类,然后选择具有此类的所有按钮,如果长度为 1 或更大,则启用 change-this 按钮,否则,我禁用它。

看一下。

$('body').on("click", "button.item-select", function (e) {
e.preventDefault();
$(this).toggleClass('select');
$(this).toggleClass('selected');

let itemsSelected = $('.selected').length;

if(itemsSelected >= 1) {
$('.change-this').prop("disabled", false);
}
else{
$('.change-this').prop("disabled", true);
}
});
.row {
background: #f8f9fa;
margin-top: 20px;
}

.col {
border: solid 1px #6c757d;
padding: 10px;
}

.selected{
border: 1px solid blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>

<button type="button" class="btn btn-danger change-this" disabled>Disabled/enabled</button>

<button type="button" class="btn btn-primary item-select">First</button>
<button type="button" class="btn btn-primary item-select">Second</button>
<button type="button" class="btn btn-primary item-select">Third</button>

关于javascript - 如果其他按钮具有特定类别,则切换按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57102510/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com