我有這樣的代碼
$('#downvotebutton').click(function() {
$(this).css('background-color', 'red !important');
console.log('foo');
//more
當點擊downvotebutton,「富」返回到控制檯,但背景顏色不會改變。 jQuery鏈接到並在頁面的其他地方工作。可能是什麼原因?
我有這樣的代碼
$('#downvotebutton').click(function() {
$(this).css('background-color', 'red !important');
console.log('foo');
//more
當點擊downvotebutton,「富」返回到控制檯,但背景顏色不會改變。 jQuery鏈接到並在頁面的其他地方工作。可能是什麼原因?
您真的需要!important
嗎?下面的工作:
$(this).css('background-color', 'red');
,或者您需要!important
:
$(this).css("cssText", "background-color: red !important;");
您不能使用!important
語句使用jQuery css()
方法。
你可以使用:
$(this).attr('style', function(_, rules) {
var newval = rules?rules:"";return newval + ';background-color: red !important;'
});
您可以使用attr(),而不是因爲css()
不能設置!important
屬性:
$('#downvotebutton').click(function() {
$(this).attr('style', 'background-color: red !important');
console.log('foo');
});
這解決了這個問題。雖然 – user3324865
@ user3324865它的工作原理,但我還是困惑,爲什麼$(this).css()不起作用,但是其他方式,請檢查我的答案 – Sergio
您可以使用css方法設置重要值,請參閱我的答案。 – heymega
試試這個..
$(docuemnt).ready(function(){
$('#downvotebutton').click(function() {
$(this).css('background-color', 'red');
console.log('color changed');
});
});
使用類代替。 .css
不支持!important
。
其實你可以使用!使用的.css()方法很重要。
cssText讓你越過第3 arguement,在這種情況下!重要
$('#downvotebutton').css("cssText", "background-color: red !important;");
希望這有助於!
你可以創建一個[jsFiddle](http://jsfiddle.net/)來演示這個問題嗎? – Mgetz
你想改變按鈕或身體或某些div的背景嗎? –
我想改變按鈕的背景顏色,這是一個div – user3324865