【问题标题】:How to change CSS with jQuery change and this如何使用 jQuery 更改更改 CSS 和 this
【发布时间】:2016-10-23 16:02:27
【问题描述】:

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

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 更改为 $(this)
  • 试过了,但没用,我应该提到它...
  • jQuery 方法不能应用于 DOM 元素。

标签: jquery css this onchange


【解决方案1】:

您需要更改最近的.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>

【讨论】:

    【解决方案2】:

    你需要的是一个 jquery 对象。这是$(this),你需要用最接近的方法遍历:

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

    【讨论】:

    • 您的答案的问题是,它会将单击的单选按钮旁边的文本变为红色,但当我单击另一个单选按钮时,它不会将其切换回蓝色。上面的@Azim 有一个可行的解决方案。
    • 当然。由于已回答并且我使用的是手持设备,因此打字速度有点慢。
    猜你喜欢
    • 2011-04-13
    • 2012-08-30
    • 2015-06-26
    • 1970-01-01
    • 1970-01-01
    • 2012-12-27
    • 1970-01-01
    • 2010-10-11
    相关资源
    最近更新 更多