最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - $(this).css not changing css values - Stack Overflow

programmeradmin8浏览0评论

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?

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?

Share Improve this question asked Feb 27, 2014 at 13:44 user3324865user3324865 1631 gold badge2 silver badges10 bronze badges 6
  • can you create a jsFiddle that demonstrates the issue? – Mgetz Commented Feb 27, 2014 at 13:45
  • do you want to change the background of the button or the body or some div? – Mukesh Soni Commented Feb 27, 2014 at 13:45
  • i want to change background-color of the button, which is a div – user3324865 Commented Feb 27, 2014 at 13:46
  • jsfiddle/Hjea4/1 – Trace Commented Feb 27, 2014 at 13:48
  • Their might be a condition that this is not pointing your target element. – Mayank Tripathi Commented Feb 27, 2014 at 13:49
 |  Show 1 more ment

6 Answers 6

Reset to default 7

Do you really need !important? Following will work:

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

Or if you need !important:

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

You cannot use !important statement using jQuery css() method.

You could use:

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

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

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

Fiddle Demo

try this..

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

Use a class instead. .css doesn't support !important.

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

Actually you can use !important with the .css() method.

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

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

Hope this helps!

发布评论

评论列表(0)

  1. 暂无评论