我有一个表单,我想通过选中一个复选框来禁用或隐藏两个输入字段。在 document.ready 上我可以很容易地做到这一点,但由于我附加了这些字段,该功能不会生效。如何使用 onClick 调用函数?
这是我的工作代码
$(function() {
$(checkbox).click(function() {
if ($('#checkbox').is(':checked')) {
$('#appTimes').find('input').attr('disabled', true);
} else {
$('#appTimes').find('input').removeAttr('disabled');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="appTimes" id="appTimes">
<input name="stopTime1" type="text" id="stopTime1" />
<input name="stopTime12" type="text" id="stopTime12" />
</div>
<input name="checkbox" type="checkbox" id="checkbox" />
这就是我想要做的:
function boxDisable(e) {
$(this).click(function() {
if ($(this).is(':checked')) {
$(e).find('input').attr('disabled', true);
} else {
$(e).find('input').removeAttr('disabled');
}
});
}
<div class="appTimes" id="appTimes">
<input name="stopTime1" type="text" id="stopTime1" />
<input name="stopTime12" type="text" id="stopTime12" />
</div>
<input name="checkbox" onclick="boxdisable(appTimes);" type="checkbox" id="checkbox" />
---编辑----------------
让我重新定义:我的代码使用 .append 来创建上述代码的多个实例。由于附加的数量是无限的,我无法用 $('#id')
定义复选框,因为可能有数百个像 $('#id1')
, $('#id2')
.. 等。我需要一个避免提及确切元素 id 的函数,它被 checkbox< 称为 onClick/strong> 并影响 beforehead div,也附加。
最佳答案
有效:)
function boxDisable(e, t) {
if (t.is(':checked')) {
$(e).find('input').attr('disabled', true);
} else {
$(e).find('input').removeAttr('disabled');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="appTimes" id="appTimes">
<input name="stopTime1" type="text" id="stopTime1" />
<input name="stopTime12" type="text" id="stopTime12" />
</div>
<input name="checkbox" onclick="boxDisable(appTimes, $(this));" type="checkbox" id="checkbox" />
关于javascript - 如何从复选框 onclick 或 onchange 调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28372466/