通过 jquery 改变 CSS class?

Changing CSS class through jquery?

我想通过 jquery 更改 CSS class 属性。我有一个不起作用的例子。单击按钮时,它应该将标签文本更改为绿色。

知道我做错了什么吗?

HTML:

<label class="somethingcustom">My Label</label><br>
<button onclick="javascript:changeColor();">click me</button>

CSS:

label.somethingcustom {color:red;}
.greenLabel label.somethingcustom {color:green;}

jquery:

function changeColor() {
    $('label.somethingcustom').parent().addClass('greenLabel');
}

http://jsfiddle.net/bq4ruekj/1/

您需要删除 .parent() 使用此代码:

function changeColor() {
    $('label.somethingcustom').addClass('greenLabel');
}

并像这样重新定义您的 css:

label.somethingcustom.greenLabel {color:green;}