我编写了创建复选框列表的代码,当我单击选项列表下方的复选框时,我希望在下方显示一个链接,用户可以单击(显示/隐藏)我无法弄清楚为什么我的代码不会工作。如果用户取消选中该框,链接就会消失,但当我单击我的复选框时没有任何反应。我想在 JQuery 中做这个修复
<!DOCTYPE html>
<html>
<div class ="container">
<head></head>
<body>
<input id="grp1" type="checkbox" value="group_1" onClick="http://google.com" />
<label for="grp1"> group 1 </label>
<div>
<input id="grp2" type="checkbox" value="group_2" onClick="http://google.com" >
group_2</label>
</div>
</body>
</html>
最佳答案
您必须使用 javascript 来隐藏/显示 html 中需要的元素。有很多方法可以做到这一点。最基本的是这样的
<!DOCTYPE html>
<html>
<body>
<div id="container">
<input id="grp1" type="checkbox" value="group_1"/>
<label for="grp1"> group 1 </label>
<br>
<input id="grp2" type="checkbox" value="group_2"/>
<label for="grp2"> group_2</label>
<!--hidden elements using css-->
<a href="#" id="url1" style="display: none;">Link for group_1</a>
<br>
<a href="#" id="url2" style="display: none;">Link for group_2</a>
</div>
<script>
//listen to the click event on the whole container
document.getElementById("container").onclick = function (e) {
//check every box if it's checked
if (document.getElementById('grp1').checked) {
document.getElementById('url1').style.display = 'block';
} else {
document.getElementById('url1').style.display = 'none';
}
if (document.getElementById('grp2').checked) {
document.getElementById('url2').style.display = 'block';
} else {
document.getElementById('url2').style.display = 'none';
}
}
</script>
</body>
</html>
当然,您可以使用不同的方法,例如在 javascript 中创建元素,然后如果您不喜欢现有隐藏元素的想法,则将其添加到 html 中。您也可以使用循环遍历复选框元素并相应地简单地显示/隐藏 url。以及更多使代码在任意数量的盒子上灵活。像这样
<!DOCTYPE html>
<html>
<body>
<div id="container">
<div id="checkBoxContainer">
<input id="grp1" type="checkbox" value="group_1"/>
<label for="grp1"> group 1 </label>
<br>
<input id="grp2" type="checkbox" value="group_2"/>
<label for="grp2"> group_2</label>
</div>
<!--hidden elements using css-->
<a href="#" id="url1" style="display: none;">Link for group_1</a>
<br>
<a href="#" id="url2" style="display: none;">Link for group_2</a>
</div>
<script>
//listen to the click event on the whole container
document.getElementById("checkBoxContainer").onclick = function (e) {
var linkNumber = 1; //This is number of the first url element with ud url1
var containerChildren = document.getElementById("checkBoxContainer").children;
//loop through the children elements
for (var i = 0; i < containerChildren.length; i++) {
var oneChild = containerChildren[i]; //catch only one child in a variable
//simply filter the input elements which are of type checkbox
if(oneChild.tagName === "INPUT" && oneChild.type === "checkbox"){
//Show or hide the url accordingly.
if (oneChild.checked) {
document.getElementById('url' + linkNumber++).style.display = 'block';
} else {
document.getElementById('url' + linkNumber++).style.display = 'none';
}
}
}
}
</script>
</body>
</html>
关于javascript - 过滤时显示和隐藏链接的 html 复选框列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44489193/