【发布时间】:2020-11-03 04:28:29
【问题描述】:
我试图能够选择一个父 div 并让它选择其各自的子单选按钮。
在这个父 div 中有一个显示/隐藏链接,它显示了这个容器中的一个 div 中的一些信息。
问题是当我单击未单击的父 div 的显示/隐藏链接时,我希望它显示/隐藏该隐藏的 div,而不选择该 div 的单选按钮/父 div。
寻找一个干净的原生 javascript 解决方案。
到目前为止,在我的代码中,它没有正确选择单选按钮的父 div,然后我想确保显示/隐藏链接不会选择尚未选择的 div。
HTML
<div class="box" onclick="check(this)">
<h3>This is div 1</h3>
<input id="radio1" name="field" type="radio" />
<div>
<div class="hiddenstuff">
You see me now
</div>
<p><a href="#" class="link" onclick="showhide(this)">show</a></p>
</div>
</div>
<br />
<div class="box" onclick="check(this)">
<h3>This is div 2</h3>
<input id="radio2" name="field" type="radio" />
<div>
<div class="hiddenstuff">
You see me now
</div>
<p><a href="#" class="link" onclick="showhide(this)">show</a></p>
</div>
</div>
CSS:
.box {
width: 300px;
height: 150px;
padding: 10px;
background-color: yellow;
cursor: pointer;
}
.checked {
border: 3px solid blue;
}
.hiddenstuff {
color: red;
padding: 10px;
display: none;
}
JS:
function check(box) {
var radioId = this.querySelectorAll('input[type="radio"]').value;
document.getElementById(radioId).click();
document.querySelectorAll(".box").forEach(function (item) {
item.classList.remove("checked");
});
if ((input[0].checked = true)) {
box.classList.add("checked");
}
return false;
}
function showhide(elem) {
var cont = elem.parentNode.previousElementSibling;
if (cont.style.display != "block") {
cont.style.display = "block";
elem.innerHTML = "hide";
} else {
cont.style.display = "none";
elem.innerHTML = "show";
}
return false;
elem.stopPropagation();
}
.box {
width: 300px;
height: 150px;
padding: 10px;
background-color: yellow;
cursor: pointer;
}
.checked {
border: 3px solid blue;
}
.hiddenstuff {
color: red;
padding: 10px;
display: none;
}
<div class="box" onclick="check(this)">
<h3>This is div 1</h3>
<input id="radio1" name="field" type="radio" />
<div>
<div class="hiddenstuff">
You see me now
</div>
<p><a href="#" class="link" onclick="showhide(this)">show</a></p>
</div>
</div>
<br />
<div class="box" onclick="check(this)">
<h3>This is div 2</h3>
<input id="radio2" name="field" type="radio" />
<div>
<div class="hiddenstuff">
You see me now
</div>
<p><a href="#" class="link" onclick="showhide(this)">show</a></p>
</div>
</div>
【问题讨论】:
-
我不得不说我不明白你的“问题..”部分,惯常的行为。
-
当我点击“显示”链接时,我希望它显示/隐藏 hiddenstuff div,但不点击父 div/单选按钮
标签: javascript