如何用 jQuery 改变 CSS 和这个

How to change CSS with jQuery change and this

我正在尝试更改所选单选按钮的文本颜色。下面的代码应该可以工作,但由于某种原因不能。

CSS:

.opts {float: left; padding-left: 5px;}

HTML:

<div class="opts"><label><input class="ws" type="radio" name="ptype" value="1">A</label></div>
<div class="opts"><label><input class="ws" type="radio" name="ptype" value="2">B</label></div>
<div class="opts"><label><input class="ws" type="radio" name="ptype" value="3">C</label></div>

jQuery

$(document).ready(function(){
  $('.ws').change(function(){
    var c = this.checked ? '#ff0000' : '#0099ff';
    this.css('color', c);
  });
}); 

我可以用 $('.opts') 替换 "this.css" 但是,当然,所有文本都会改变颜色。我的问题是无法使 "this" 工作。有帮助吗?

您需要像下面这样更改最近的 .opts 的颜色。

$('.ws').change(function() {
    $('.opts').css('color', '#0099ff'); 
    $(this).closest('.opts').css('color', '#ff0000');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="opts"><label><input class="ws" type="radio" name="ptype" value="1">A</label></div>
<div class="opts"><label><input class="ws" type="radio" name="ptype" value="2">B</label></div>
<div class="opts"><label><input class="ws" type="radio" name="ptype" value="3">C</label></div>

您需要的是一个 jquery 对象。即 $(this) 需要用 closest 方法向上遍历:

 $(this).closest('.opts').css('color', c);