![](/img/trans.png)
[英]how can i call carousel() an external javascript function into html file?
[英]How can I modify an HTML element from an external Javascript File?
我想在选中复选框时显示输入。 因此,我创建了一个 js 函数来执行此操作,当我在 HTML 文件上编写该函数时,它可以工作。 但我想将该函数写入外部 Javascript 文件并从那里使用它。 我该怎么做?
HTML代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Complement Selection</title>
</head>
<body>
<form class="formComplement" action="../php/complementSelectionSave.php" method="POST">
<div class="mainContainer">
<input type="checkbox" name="hood" id="hood" onclick="showInput()">
<label for="hood">Hood</label><br>
<div class="inputBox" id="hoodNum" style="display:none">
<input type="number" name="hoodNumber" id="hoodNumber" required="" value="">
<label for="hoodNumber">Number of Hoods</label>
<br>
</div>
</div>
<br><br><br>
<input type="submit" value="Next" class="nextButton"/>
</form>
<script src="showInput.js"></script>
</body>
</html>
Javascript文件:
function showInput() {
var checkBox = document.getElementById("hood");
var inputBox = document.getElementById("hoodNum");
if (checkBox.checked == true) {
inputBox.style.display = "block";
} else {
inputBox.style.display = "none";
}
}
编辑:出现此错误:
showInput.js:4 未捕获的类型错误:无法读取 showInput.js:4 处的 null 属性“已检查”
如果您在这里需要 javascript 的唯一原因是更改类,显示/隐藏元素,而不是您可以做的是用纯 css 和 html 编写代码,使用 input:checked 来更改可见性。
此外,nextButton 应该可以被 css 定位,就像元素或其父元素是相同的 lvl 并且在输入之后
#hood:checked ~ .nextButton { display: block; } .nextButton {display: none;}
<input type="checkbox" name="hood" id="hood"> <label for="hood">Hood</label><br> <input type="submit" value="Next" class="nextButton"/>
尝试onchange
而不是onclick
,并清除 HTML - 该功能按预期工作! :)
function showInput() { var checkBox = document.getElementById("hood"); var inputBox = document.getElementById("hoodNum"); if (checkBox.checked == true) { inputBox.style.display = "block"; } else { inputBox.style.display = "none"; } }
<form class="formComplement" action="" method="POST"> <div class="mainContainer"> <input type="checkbox" name="hood" id="hood" onchange="showInput()"> <label for="hood">Hood</label><br> <div class="inputBox" id="hoodNum" style="display:none"> <input type="number" name="hoodNumber" id="hoodNumber" required="" value=""> <label for="hoodNumber">Number of Hoods</label> <br> </div> </div> <br><br><br> <input type="submit" value="Next" class="nextButton" /> </form>
(我从form
删除了操作,因为它在代码段中没有意义。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.