使用 JQuery 更改具有相同类的所有 div 的 CSS 值,但前提是选中包含的复选框

我是这个世界的新手,发现自己处在一个非常陡峭的学习曲线上。到目前为止,我已经通过浏览这个网站设法解决了所有问题,但是这个让我感到难过!我已经给了它一整天,但无法取得进展,所以我希望有人能提供帮助。


我有 2 个角色,学生和评估员。


学生完成他们的工作,然后评估员对其进行标记,如果答案足够,则会勾选一个复选框。


然后学生查看他们的作业,应该会看到带有已选中复选框的答案的绿色背景,未选中的则没有背景。


目前我的代码正在更改具有相同类的所有 div 的背景颜色,无论复选框是否被选中。


非常感谢任何关于我哪里出错的帮助。


HTML 表单中的示例问题:


$(document).ready(function() {


  $('.answer').each(function() {

    if ($(this).find('input.cb:checked').prop('checked')) {


      $('.answer').css("background-color", "#a5de76");


    }

  });

});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<div class="text-left">1. Describe the procedures in place when a steward supervises spectator entry.</div>

<p></p>

<div class="answer"><textarea id="U1Q1" name="U1Q1" rows="5" cols="70"><?php echo htmlspecialchars($row['U1Q1'])?></textarea>

  <?php echo '<input class="cb" type="checkbox" name="n" class="hidden" value="v"' . ($row['U1Q1R']==1 ? ' checked="checked"' : '') . '>';?>

  <input style="color:blue" id="textfield" name="U1Q1F" class="textfields" type="text" value="<?php echo htmlspecialchars($row['U1Q1F'])?>" readonly />

</div>

这是它当前在屏幕上的样子(一旦我的代码工作,复选框将被隐藏:


学生页面


忽然笑
浏览 81回答 1
1回答

杨魅力

您只需要使用当前上下文this并更改:$('.answer').css("background-color", "#a5de76");到$(this).css("background-color", "#a5de76");因此,只有当前选中的答案背景颜色被更改。完整代码:$(document).ready(function() {&nbsp; $('.answer').each(function() {&nbsp; &nbsp; if ($(this).find('input.cb').prop('checked')) {&nbsp; &nbsp; &nbsp; $(this).css("background-color", "#a5de76");&nbsp; &nbsp; }&nbsp; });});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><div class="text-left">1. Describe the procedures in place when a steward supervises spectator entry.</div><p></p><div class="answer">&nbsp; <textarea id="U1Q1" name="U1Q1" rows="2" cols="70"></textarea>&nbsp; <input class="cb" type="checkbox" name="n" class="hidden" value="v" checked>&nbsp; <input style="color:blue" id="textfield" name="U1Q1F" class="textfields" type="text" value="" readonly /></div><div class="answer">&nbsp; <textarea id="U1Q1" name="U1Q1" rows="2" cols="70"></textarea>&nbsp; <input class="cb" type="checkbox" name="n" class="hidden" value="v">&nbsp; <input style="color:blue" id="textfield" name="U1Q1F" class="textfields" type="text" value="" readonly /></div><div class="answer">&nbsp; <textarea id="U1Q1" name="U1Q1" rows="2" cols="70"></textarea>&nbsp; <input class="cb" type="checkbox" name="n" class="hidden" value="v" checked>&nbsp; <input style="color:blue" id="textfield" name="U1Q1F" class="textfields" type="text" value="" readonly /></div>
打开App,查看更多内容
随时随地看视频慕课网APP