jQuery 在当前选定的按钮旁边显示元素

jQuery show element beside currently selected button

本文关键字:按钮 显示 元素 jQuery      更新时间:2023-09-26

我的每个单选按钮都在一个div内,紧挨着输入(radio)我在一个范围内有一些文本,CSS设置为显示:none。由于我有多个单选按钮,因此我正在尝试将范围设置为仅显示所选单选按钮旁边的范围。思潮?

这是我目前拥有的。

$('input:checked').next().show();

这是我正在尝试构建的完整测验的小提琴

http://jsfiddle.net/YSSWL/96/

随意批评我的jquery的其余部分,因为我可能过于复杂化了某些事情。我对jqueryjs(正在研究它)没有太多经验。

解决方案编辑:正如Chausser指出的那样,我可以使用

$('input:checked').parent().find('span').show();

选择最接近所选输入父级的范围并应用 .show();

您可以使用:

$('input:checked').parent().find('span').show();

我更新了您的 html 以使用一些一致的类并修复了您的重置函数。对于工作代码检查:

http://jsfiddle.net/YSSWL/106/

你可以用CSS完全解决这个问题:

.incorrect .incor { display: inline; } 

http://jsfiddle.net/YSSWL/105/

我认为这是一个更好的写法。 更灵活一点。 对不起,我删除了你的一堆东西,以明确发生了什么。

.JS:

$(document).ready(function () {
    $(document).on('click', '#radiochk1', function(){
        var checkedRadio = $('input[name="question1"]:checked');        
        $('.correct, .incorrect').removeClass('correct').removeClass('incorrect');
        if(checkedRadio.hasClass('rightAnswer')){
            checkedRadio.parent().find('span.answer').addClass('correct');
        }else{
            checkedRadio.parent().find('span.answer').addClass('incorrect');
        }
    });
    $(document).on('click', '#resetq1', function(){
        $('.correct, .incorrect').removeClass('correct').removeClass('incorrect');
        $('input[name="question1"]').attr('checked', false);
    });
});

.HTML:

<form class="ra">
    <div class="cor">
        <input type="radio" name="question1" class="c1" />A. Choice A<span class="hiddencorr">Correct answer</span>
    </div>
    <div class="inc">
        <input type="radio" name="question1" class="i1" />B. <span class="answerswer">Choice B</span>
    </div>
    <div class="inc">
        <input type="radio" name="question1" class="i2 rightAnswer" />C. <span class="answerswer">Choice C</span>
    </div>
    <div class="inc">
        <input type="radio" name="question1" class="i3" />D. <span class="answerswer">Choice D</span>
    </div>
    <div class="inc">
        <input type="radio" name="question1" class="i4" />E. <span class="answerswer">Choice E</span>
    </div>
</form>
<p class="rationale1"><b>Rationale:</b> 
    <br />
    <br /><span class="rattext">Explanation of what was done wrong.</span>
 </p>
 <button id="radiochk1" class="checkhide">Check your answer</button>
 <button id="resetq1" class="reset">Reset</button>