使用jQuery根据值更改下拉列表的背景颜色

问题描述:

这是HTML代码

<label class="col-lg-6">37.sample 1 </label>
<select class="form-control" id="colorchg">
  <option></option>
  <option value="green">YES</option>
  <option value="red">NO</option>
  <option value="gray">N/A</option>
</select>

<label class="col-lg-6">38. sample 2</label>
<select class="form-control" id="colorchg">
  <option></option>
  <option value="green">YES</option>
  <option value="red">NO</option>
  <option value="gray">N/A</option>
</select>

<label class="col-lg-6">39. sample 3</label>
<select class="form-control" id="colorchg">
  <option></option>
  <option value="green">YES</option>
  <option value="red">NO</option>
  <option value="gray">N/A</option>
</select>

HTML输出

:

脚本

$(document).ready(function() {
  $("#colorchg").each(function() {
    var color = $("#colorchg").val();
    $(this).css("background", color);
  });
  $("#colorchg").change(function() {
    var color = $("#colorchg").val();
    $(this).css("background", color);
  });
});

但是它只会更改第一个实例的背景颜色

But it only changes the bg-color of the first instance

为了在每个下拉列表中实施脚本,应该如何更改脚本

How should the script change in order to implement it in every dropdown list

尝试一下:

$(document).ready(function() {
  $(".colorchg").each(function() {
    $(this).css("background", $(this).val());
  });
  $(".colorchg").change(function() {
    $(this).css("background", $(this).val());
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="col-lg-6">37.sample 1 </label>
<select class="form-control colorchg">
  <option></option>
  <option value="green">YES</option>
  <option value="red">NO</option>
  <option value="gray">N/A</option>
</select>

<label class="col-lg-6">38. sample 2</label>
<select class="form-control colorchg">
  <option></option>
  <option value="green">YES</option>
  <option value="red">NO</option>
  <option value="gray">N/A</option>
</select>

<label class="col-lg-6">39. sample 3</label>
<select class="form-control colorchg">
  <option></option>
  <option value="green">YES</option>
  <option value="red">NO</option>
  <option value="gray">N/A</option>
</select>

通过使用类,jQuery将找到多个要使用的元素.ID必须是唯一的,因此假定它只是一个元素.

By using classes, jQuery will find more than one element to use. ID's need to be unique, so it assumes it's only one element.

您应该使用 this ,而不是在函数中再次搜索该值,否则背景将更改为第一个选项所设置的值.

Instead of searching for the value again in the functions, you should use this, otherwise the backgrounds will change to whatever the first option is set to.