我的html视图上有一个复选框,如下所示:
<input type="checkbox" id="hasPrereqBlock" name="hasPrereqBlock" onchange="hasPrereqBlockHandler(this)">由它触发的函数看起来是这样的:
function hasPrereqBlockHandler(cb){
if (cb.checked){
$("#campaignPrereqBlockRevDiv").show();
$("#instruction_1_RevDiv_M").hide();
$("#instruction_2_RevDiv").show();
} else {
$("#campaignPrereqBlockRevDiv").hide();
$("#instruction_1_RevDiv_M").show();
$("#instruction_2_RevDiv").hide();
}
}当我加载页面时,我想执行这个函数,并给它一个对复选框的引用,这样它就只显示想要的东西,因为复选框的状态,所以我有这个函数:
$(document).ready(function() {
hasPrereqBlockHandler($("#hasPrereqBlock"));
});我也尝试过使用document.getElementById("hasPrereqBlock")而不是$("#hasPrereqBlock"),但这3个元素都会显示出来,只有当我单击复选框时它们才会隐藏起来。为什么我的代码不能工作?
function hasPrereqBlockHandler(cb) {
if (cb.checked) {
$("#campaignPrereqBlockRevDiv").show();
$("#instruction_1_RevDiv_M").hide();
$("#instruction_2_RevDiv").show();
} else {
$("#campaignPrereqBlockRevDiv").hide();
$("#instruction_1_RevDiv_M").show();
$("#instruction_2_RevDiv").hide();
}
}
$(document).ready(function() {
console.log("document ready");
hasPrereqBlockHandler($("#hasPrereqBlock"));
});#campaignPrereqBlockRevDiv,
#instruction_2_RevDiv {
display: none;
}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="hasPrereqBlock" name="hasPrereqBlock" onchange="hasPrereqBlockHandler(this)">
<div id="instruction_1_RevDiv_M">Review 1</div>
<br>
<div id="instruction_2_RevDiv">Review 2</div>
<br>
<div id="campaignPrereqBlockRevDiv">Campaing</div>
发布于 2021-05-31 15:53:03
您的jQuery对象没有.checked。如果你console.log cb.checked,它返回undefined而不是布尔值,所以你知道有问题。jQuery checkbox对象上不存在.checked。
更改:
cb.checked进入:
cb.prop('checked')发布于 2021-05-31 16:08:00
你把JavaScript和jQuery混在一起了!正如dcangulo所述,将您发送的元素更改为文档就绪部分中的函数:
$(document).ready(function() {
hasPrereqBlockHandler($("#hasPrereqBlock").get(0));
});get返回给定索引处的元素,由于存在一个元素(您使用的是一个ID,所以我假设只有一个),所以它发送第一个元素。发送到函数的元素与检查输入时发送的this值相同。
https://stackoverflow.com/questions/67769725
复制相似问题