2014-02-27 30 views
3

我有這樣的代碼

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

當點擊downvotebutton,「富」返回到控制檯,但背景顏色不會改變。 jQuery鏈接到並在頁面的其他地方工作。可能是什麼原因?

+0

你可以創建一個[jsFiddle](http://jsfiddle.net/)來演示這個問題嗎? – Mgetz

+0

你想改變按鈕或身體或某些div的背景嗎? –

+0

我想改變按鈕的背景顏色,這是一個div – user3324865

回答

6

您真的需要!important嗎?下面的工作:

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

,或者您需要!important

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

您不能使用!important語句使用jQuery css()方法。

你可以使用:

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

您可以使用attr(),而不是因爲css()不能設置!important屬性:

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

Fiddle Demo

+0

這解決了這個問題。雖然 – user3324865

+0

@ user3324865它的工作原理,但我還是困惑,爲什麼$(this).css()不起作用,但是其他方式,請檢查我的答案 – Sergio

+0

您可以使用css方法設置重要值,請參閱我的答案。 – heymega

1

試試這個..

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

其實你可以使用!使用的.css()方法很重要。

cssText讓你越過第3 arguement,在這種情況下!重要

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

希望這有助於!