我正在尝试开发一个 JQuery 脚本,通过根据不同复选框的状态将禁用属性设置为 true 来更改复选框的状态。
我有三个复选框 - 暂停、选项 1 和选项 2
使用下面的代码,然后单击暂停的复选框,其他两个将被禁用。如果我取消选中暂停的框,它们就可用(禁用属性已删除)。
我想在页面加载时应用相同的逻辑。我的代码如下:
(function( $ ) {
'use strict';
$( document ).ready(function() {
if( $('input[name="suspended"]').is(':checked')){
console.log( "Suspended is checked" );
$('input[name="option1"]' ).attr("disabled", true);
$('input[name="option2"]' ).attr("disabled", true);
}
else{
console.log( "Suspended is unchecked" );
$('input[name="option1"]' ).removeAttr("disabled");
$('input[name="option2"]' ).removeAttr("disabled");
}
$( 'input[name="suspended"]' ).change( function( e ){
e.preventDefault;
if ($(this).is(':checked')) {
$('input[name="option1"]' ).attr("disabled", true);
$('input[name="option2"]' ).attr("disabled", true);
}else {
$('input[name="option1"]' ).removeAttr("disabled");
$('input[name="option2"]' ).removeAttr("disabled");
}option2
} );
});
})( jQuery );
我显然已经解决了点击情况的更改状态,但无法弄清楚为什么它在页面加载时不起作用。我可以获得 concole.log 消息来显示页面加载时的状态,但更改复选框的状态。
我可以看出您喜欢 JQuery,但即使在普通 JavaScript 中,它也不必太复杂。您无需执行所有测试,只需为
disabled
属性指定复选框上 checked
属性的值即可。
我喜欢使用
<fieldset>
,在这种情况下它可能有意义,因为您有多个要禁用的输入元素。
document.addEventListener('DOMContentLoaded', e => {
let form = document.forms.form01;
form.options.disabled = form.suspended.checked;
});
document.forms.form01.suspended.addEventListener('change', e => {
e.target.form.options.disabled = e.target.checked;
});
fieldset {
border: none;
display: flex;
flex-direction: column;
}
<form name="form01">
<label><input type="checkbox" name="suspended">Suspended</label>
<fieldset name="options">
<label>Option 1:<input type="text" name="option1"></label>
<label>Option 2:<input type="text" name="option2"></label>
</fieldset>
</form>