对不同的ID使用相同的功能来显示元素

问题描述 投票:-1回答:2

所以我仍然还是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?

我希望这是可以理解的。预先感谢。

javascript html forms onclick
2个回答
0
投票
您只需要将该ID更改为一个类(因为您不能两次使用相同的ID),就可以删除onlick属性,并将单选按钮更改为复选框(因为无法取消选择一个单选按钮)。

<!-- First Question radio button --> <input class="form-check-input" type="checkbox" name="rb_pg" value="Ja"> <div class="furtherQuestion" style="display:none"> <span>another conditioned question 1</span> </div> <!-- Second Question radio button --> <input class="form-check-input" type="checkbox" name="rb_radio" value="Ja"> <div class="furtherQuestion" style="display:none"> <span>another conditioned question 2</span> </div>

然后使用这行jquery:

$('input.form-check-input').on('change', function(){
    $(this).next('.furtherQuestion').toggle();
});

https://jsfiddle.net/Lz6wrebg/

并且如果您需要将它们用作单选按钮,只需确保它们具有相同的名称,以使它们在单击时彼此取消选择。


<!-- First Question radio button --> <input class="form-check-input" type="radio" name="rb_radio" value="Ja"> <div class="furtherQuestion" style="display:none"> <span>another conditioned question 1</span> </div> <!-- Second Question radio button --> <input class="form-check-input" type="radio" name="rb_radio" value="Ja"> <div class="furtherQuestion" style="display:none"> <span>another conditioned question 2</span> </div>

然后使用此jquery:

$('input.form-check-input').on('change', function(){
    $('.furtherQuestion').slideUp(200);
    $(this).next('.furtherQuestion').slideDown();
});

https://jsfiddle.net/Lz6wrebg/1/

© www.soinside.com 2019 - 2024. All rights reserved.