HTML 中的每个字段在文本输入旁边都有一个复选框,如下所示:
<div class="field">
<input type="checkbox" id="checkbox1" />
<input type="text" id="textbox1" />
</div>
<div class="field">
<input type="checkbox" id="checkbox2" />
<input type="text" id="textbox2" />
</div>
使用 jQuery's Attribute Starts With Selectors ,很容易将每个复选框上的点击事件与其同级文本框的禁用状态联系起来——这已经很有效了:
$("input[id^='checkbox']").click(function() {
$(this).siblings().prop("disabled", !this.checked);
});
我想不通的是一个类似的简洁语句,我可以运行一次(从另一个事件),它将根据相关复选框的当前选中状态切换所有这些文本框。这大致是我认为它应该是的,但它只是切换所有这些而不是根据需要单独切换 - 即它不起作用:
$("input[id^='textbox']").prop("disabled", $(this).prev().is(':checked'));
我也尝试过使用更改处理程序进行此操作,但是当复选框本身重新启用时它不会触发。
对我有什么建议吗?
最佳答案
如果我没理解错的话,如果相应的复选框被选中,您想启用文本输入。建议的方法:
$('input[type="checkbox"]').on('change', function() {
$(this).next().prop('disabled', !this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="field">
<input type="checkbox" id="checkbox1" />
<input type="text" disabled id="textbox1" />
</div>
<div class="field">
<input type="checkbox" id="checkbox2" />
<input type="text" disabled id="textbox2" />
</div>
关于javascript - jQuery:基于兄弟复选框整体切换禁用状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44864145/