javascript - 对不同的ID使用相同的函数来显示元素
问题描述
所以我仍然是javascript和一般编码的初学者。我需要为我的学习从头开始创建一个调查网站。
我希望有可选问题,这些问题仅在通过单击该单选按钮以“是”回答之前的问题时才显示。因此,我的两个问题的 html 如下所示:
<!-- First Question radio button -->
<input onclick="showQuestion()" class="form-check-input" type="radio" name="rb_pg" value="Ja">
<div id="furtherQuestion" style="display:none">
<!-- another conditioned question 1 -->
</div>
<!-- Second Question radio button -->
<input onclick="showQuestion()" class="form-check-input" type="radio" name="rb_radio" value="Ja">
<div id="furtherQuestion" style="display:none">
<!-- another conditioned question 2 -->
</div>
显示容器的函数 showQuestion() 如下所示:
function showQuestion() {
var x = document.getElementById('furtherQuestion');
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
现在,当我单击第一个和第二个问题的单选按钮“rb_pg”和“rb_radio”时,只有第一个问题在显示无和块之间切换。
我知道我目前正在使用相同的 ID“furtherQuestion”两次。这是我需要你帮助的地方。
如何将 ID“furtherQuestion”中的参数传递给函数,以便我可以重用此函数来显示与之前通过单选按钮回答的问题相关的 div?
我希望这是可以理解的。提前致谢。
解决方案
您可以简单地将 id 作为参数传递给事件处理程序:showQuestion('furtherQuestion_1')
。
此外,这就是我构建您的代码的方式。
function showQuestion(id) {
const $allFurtherQuestionBlocks = document.querySelectorAll('.furtherQuestion');
for (let $el of $allFurtherQuestionBlocks) {
$el.style.display = "none";
}
const $el = document.querySelector(`#${id}`);
$el.style.display = "block";
}
<input onclick="showQuestion('furtherQuestion_1')" type="radio" name="rb" value="Ja">
<input onclick="showQuestion('furtherQuestion_2')" type="radio" name="rb" value="Ja">
<div id="furtherQuestion_1" class="furtherQuestion" style="display:none">
<p>Another conditioned question 1</p>
</div>
<div id="furtherQuestion_2" class="furtherQuestion" style="display:none">
<p>Another conditioned question 2</p>
</div>
推荐阅读
- matlab - 通过 Visa 从 Keysight 仪器读取数据接收缓冲区警告
- javascript - 从屏幕阅读器可访问性中隐藏父元素而不隐藏其子元素
- terraform - gitlab CI 没有在用户主文件夹中创建 kube 配置
- sql - 数据行开始和结束的 SQL
- javascript - Vue 3 传递数组警告:无关的非道具属性已传递给组件但无法自动继承
- google-cloud-firestore - Firestore 是否需要为每个查询字段组合使用单独的索引?(9 FAILED_PRECONDITION:查询需要索引。)
- c# - 多次调用 Azure 表存储以请求少于 10 行
- google-sheets - VLOOKUP 公式在一张纸上工作,但不在另一张纸上
- pandoc - pandoc 2.5 拒绝下划线(.tex 到 .md)
- sql-server - 如何在条件字符串列表的where中使用sql子字符串