首页 > 解决方案 > 对不同的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?

我希望这是可以理解的。提前致谢。

标签: javascripthtmlformsonclick

解决方案


您可以简单地将 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>


推荐阅读