【发布时间】:2021-05-31 07:45:28
【问题描述】:
我的 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>
【问题讨论】:
-
尝试替换为
$("#hasPrereqBlock")[0] -
您需要牢记您使用的是原生 JS 还是 jQuery。
$("#hasPrereqBlock")是一个 jQuery 对象,没有.checked(请注意,您的问题标题是基于错误的假设,请始终像console.log("document ready");这样进行基本调试以尝试缩小问题范围) -
谢谢@ChrisG,这是一个很好的观点,“文档准备就绪”没有被打印出来,但我不明白为什么,因为 jQuery 的工作除此之外..
-
这很奇怪,因为实际的问题是别的。我已经编辑了你的 sn-p 并且按预期调用了该函数。
-
好的,我添加了一个
window.addEventListener('load', (event => {});,这可以正常工作。但我使用的是 jQueryhasPrereqBlockHandler($("#hasPrereqBlock"));,不是吗?那么为什么 jQuery 可以在这个 JS-load 函数中工作,而不是在 jQuery 文档就绪函数中呢?
标签: javascript jquery document-ready