【发布时间】:2021-09-08 06:58:53
【问题描述】:
我有一个 javascript function,它在每个 button 旁边插入一个 checkbox 类型的 input。当第一个复选框被点击时,其各自的按钮被禁用,并且该复选框在页面被刷新时保持不变,同样,当再次点击该复选框时,该按钮被重新启用并在页面刷新后保持。
我的目标是,当单击与按钮相关的复选框时,只有该按钮被禁用。发生的事情是只有第一个复选框触发function,当它被触发时,其他复选框也是。当我尝试单击第二个或第三个复选框时,此功能不起作用。
我认为这是因为forEach()。我需要的是让这个功能为每个按钮单独工作,并在页面刷新后保持复选框启用/禁用。
<div id="accordion">
<% turmas.forEach((turma)=> { %>
<div class="card">
<div class="card-header" id="headingThree>">
<h5 class="mb-0 d-flex">
<div id="billing">
<input type="checkbox" id="billing-checkbox" checked>
<button class="btn btn-info text-white collapsed d-flex align-center" data-toggle="collapse" data-target="#<%= turma.nome %>" aria-expanded="false" aria-controls="<%= turma.nome %>" id="btn">
<%= turma.nome %>
</button>
</div>
</h5>
</div>
</div>
<% }) %>
$(document).ready(function() {
$('#billing-checkbox').prop('checked', localStorage.getItem('buttonDisabled') !== "disabled");
toggleBilling({
target: $('#billing-checkbox')[0]
})
$('#billing-checkbox').on('change', toggleBilling);
});
function toggleBilling(e) {
$('#billing button').attr('disabled', !e.target.checked)
localStorage.setItem('buttonDisabled', $('#billing button').attr('disabled'));
}
24/06/21 更新:
用户@RoryMcCrossan 创建了一个解决方案,使每个复选框为每个按钮单独工作,但是有一个问题,当按钮被禁用时,当尝试重新激活它时,它不会在谷歌浏览器上再次启用它。
jQuery($ => {
$('.billing-checkbox').on('change', e => {
$(e.target).next('button').prop('disabled', !e.checked);
});
});
这是允许复选框在刷新页面后保持启用/禁用的代码
$(document).ready(function() {
$('.billing-checkbox').prop('checked', localStorage.getItem('buttonDisabled') !== "disabled");
toggleBilling({
target: $('.billing-checkbox')[0]
})
$('.billing-checkbox').on('change', toggleBilling);
});
function toggleBilling(e) {
$('.billing input[type="button"]').attr('disabled', !e.target.checked)
localStorage.setItem('buttonDisabled', $('.billing input[type="button"]').attr('disabled'));
}
理想的情况是同时加入这两个功能,但我一直在尝试,但没有成功。
【问题讨论】:
-
链接中的代码损坏
-
你使用
id的,改成类 -
@LawrenceCherone 你指的是
id#headingThree>? -
不,所有的 id,特别是用于选择器的那些
标签: javascript jquery node.js arrays foreach