javascript $(this).css 不改变 css 值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22070397/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 22:21:31  来源:igfitidea点击:

$(this).css not changing css values

javascriptjquerycss

提问by user3324865

I have this code

我有这个代码

$('#downvotebutton').click(function() {
    $(this).css('background-color', 'red !important');
    console.log('foo');
    //more

When downvotebutton is clicked, 'foo' is returned to the console but the background-color doesn't change. jQuery is linked to and works elsewhere in the page. what could possibly be the cause?

单击 downvotebutton 时,'foo' 返回到控制台,但背景颜色不会改变。jQuery 链接到页面中的其他地方并在其他地方工作。可能是什么原因?

回答by Sergio

Do you really need !important? Following will work:

你真的需要!important吗?以下将起作用:

$(this).css('background-color', 'red');

Or if you need !important:

或者,如果您需要!important

$(this).css("cssText", "background-color: red !important;");

回答by A. Wolff

You cannot use !importantstatement using jQuery css()method.

您不能使用!importantjQuerycss()方法使用语句 。

You could use:

你可以使用:

$(this).attr('style', function(_, rules) { 
     var newval = rules?rules:"";return newval + ';background-color: red !important;' 
});

回答by Felix

You can use attr()instead since css()cannot set !importantproperty:

您可以使用attr()代替,因为css()无法设置!important属性:

$('#downvotebutton').click(function() {
    $(this).attr('style', 'background-color: red !important');
    console.log('foo');
});

Fiddle Demo

小提琴演示

回答by kamesh

try this..

试试这个..

$(docuemnt).ready(function(){
$('#downvotebutton').click(function() {
    $(this).css('background-color', 'red');
    console.log('color changed');
});
});

回答by mbcrute

Use a class instead. .cssdoesn't support !important.

改用类。.css不支持!important

http://bugs.jquery.com/ticket/11173

http://bugs.jquery.com/ticket/11173

回答by heymega

Actually you canuse !important with the .css() method.

实际上,您可以将 !important 与 .css() 方法一起使用。

cssText allows you to pass over a 3rd arguement, in this case !important

cssText 允许您传递第三个论点,在这种情况下 !important

$('#downvotebutton').css("cssText", "background-color: red !important;");

Hope this helps!

希望这可以帮助!