如何通过单击另一个元素来更改一个元素的颜色 - jquery

时间:2013-08-26 07:01:00

标签: jquery

我在英语/泰语网站上进行了多项选择测试。每行有一个问题和4个答案选择,布局基本上是50X5矩阵。

    <div id="question">
        <p class="word_test">1<span class="1 color_up audio" id="b1e01">the </span></p>
        ...
        <p class="word_test">50<span class="50 color_up audio" id="b1e50">if </span></p>
    </div>
    <div id="answers">
        <div id="col_a">
            <p class="word_test">A:<span class="1 color_up audio" id="b1t01">คำนำหน้านาม</span></p>
                ...
            <p class="word_test">A:<span class="50 color_up incorrect">มัน </span></p>
        </div>
        <div id="col_b">
          ...
         </div>
        <div id="col_c">
          ...
        </div>
        <div id="col_d">
            <p class="word_test">D:<span class="1 color_up incorrect">เลอะ </span></p>
                ...
            <p class="word_test">D:<span class="50 color_up incorrect">เป็น อยู่ คือ </span>    </p>
        </div>
    </div>

当用户点击A,B,C或D中的一个选项时,我希望该行中的问题项目变为绿色(正确)或红色(不正确)。我的问题是如何在任何一行中将点击的目标(A,B,C或D)链接到requicolor更改。我可以看到addClass和removeClass将处理颜色变化,但我看不到如何在点击的答案和问题项之间建立连接。我已经对每列中的行进行了编号,以便可以引用相应的问题,但我不知道这是否必要。谢谢你的帮助。

2 个答案:

答案 0 :(得分:1)

请参阅.click()

$("#other").click(function() {
  $("#target").css("background", "red");
});

答案 1 :(得分:0)

HTML&amp; CSS

我认为您不需要锚点击,因为这次脚本会在触发单选按钮后立即检查答案。

<style type="text/css">
    .hide { display:none; }
</style>

<div class="questions">
    <p>Q1</p>
    <label><input type="radio" name="q1" value="a" />Q1 A</label>
    <label><input type="radio" name="q1" value="b" />Q1 B</label>
    <label><input type="radio" name="q1" value="c" />Q1 C</label>
</div>

<div class="questions hide">
    <p>Q2</p>
    <label><input type="radio" name="q2" value="a" />Q2 A</label>
    <label><input type="radio" name="q2" value="b" />Q2 B</label>
    <label><input type="radio" name="q2" value="c" />Q2 C</label>
</div>

<div class="questions hide">
    <p>Q3</p>
    <label><input type="radio" name="q3" value="a" />Q3 A</label>
    <label><input type="radio" name="q3" value="b" />Q3 B</label>
    <label><input type="radio" name="q3" value="c" />Q3 C</label>
</div>

使用jQuery的Javascript

var answers = {q1: 'a', q2: 'b', q3: 'a'};
/* True Answers: ↑ "a" ,  ↑ "b"  ,  ↑ "a" */
$('input:radio').click(function() {
    var container = $(this).parents('div');
    var question = $(this).attr('name');
    var answer = $(this).val();

    alert(answers[question] == answer);

    container.addClass('hide');
    container.next().removeClass('hide');
});

只需根据需要修改脚本即可。希望这次适合你。 =))

相关问题