我有这段代码
$('#downvotebutton').click(function() {
$(this).css('background-color', 'red !important');
console.log('foo');
//more
单击downvotebutton时,'foo'将返回到控制台,但背景颜色不会更改。 jQuery链接到页面的其他地方并在其他地方工作。可能是什么原因?
答案 0 :(得分:7)
你真的需要!important
吗?以下工作:
$(this).css('background-color', 'red');
或者如果您需要!important
:
$(this).css("cssText", "background-color: red !important;");
答案 1 :(得分:3)
您不能使用jQuery !important
方法使用css()
语句。
您可以使用:
$(this).attr('style', function(_, rules) {
var newval = rules?rules:"";return newval + ';background-color: red !important;'
});
答案 2 :(得分:1)
您可以使用attr(),因为css()
无法设置!important
属性:
$('#downvotebutton').click(function() {
$(this).attr('style', 'background-color: red !important');
console.log('foo');
});
<强> Fiddle Demo 强>
答案 3 :(得分:1)
试试这个..
$(docuemnt).ready(function(){
$('#downvotebutton').click(function() {
$(this).css('background-color', 'red');
console.log('color changed');
});
});
答案 4 :(得分:1)
改为使用班级。 .css
不支持!important
。
答案 5 :(得分:1)
实际上你可以使用!important与.css()方法一样重要。
cssText允许你传递第三个争论,在这种情况下!重要
$('#downvotebutton').css("cssText", "background-color: red !important;");
希望这有帮助!