jQuery不能分配给一个函数结果 [英] jQuery cannot assign to a function result
问题描述
我在以下代码中遇到上面标题中的错误:
I am getting the error in the title above in the following code:
$j(".table").delegate('td','click', function(e) {
//alert($j(this).parent().css('background-color'));
if ($j(this).parent().css('background-color') == 'transparent')
$j(this).parent().css('background-color') = '#eee';
else {
$j(this).parent().css('background-color') = 'transparent';
}
});
我不明白为什么会收到这个错误,使用赋值运算符 ==
来比较字符串
I don't understand why I'd be getting this error, as I have made sure I am using the assignment operator ==
to compare the strings
推荐答案
2个问题与您的问题:第一个已经由@Mike Vranckx回答,正确的使用 .css()
setter传递第二个参数设置为value。
There are 2 issues with your question: first one is already answered by @Mike Vranckx, the correct usage of .css()
setter is passing a second argument to set as value.
另一个问题是,你的条件永远不会是真的,我会在这个答案解决。如果你按照我的建议解决它,你不需要 .css()
。
The other problem is that your condition will never be true, I'll address it in this answer. If you fix it in the way I suggest, you won't be needing .css()
.
计算CSS值 ,它们是从 getComputedStyle
/ jQuery的 .css()
返回的,不是你在代码中创建的
Computed CSS values, which are returned from getComputedStyle
/jQuery's .css()
, are not exactly what you've authored in your code -- they suffer transformations when parsed into the CSSOM.
例如,在Chrome中:
For instance, in Chrome:
body { background-color: transparent; }
console.log( $('body').css('background-color') ); //returns "rgba(0, 0, 0, 0)"
这就是为什么你的 $ ...)('background-color')=='transparent'
条件总是false。
That's why your $(...).('background-color') == 'transparent'
condition is always false.
最干净,跨浏览器的解决方案是使用类应用样式( .addClass()
, removeClass()
, toggleClass()
),并使用 .hasClass()$ c $进行条件检查c>
。
The most clean and cross-browser solution is to apply styling with classes (.addClass()
, removeClass()
, toggleClass()
) and do conditional checks with .hasClass()
.
在你的情况下, .toggleClass
这里有一个简单的方法来写您的逻辑( 小提示 ):
In your case though, .toggleClass
should suffice. Here's a simple way to write your logic (fiddle):
$j(".table").on('click', 'td', function() {
$j(this).parent().toggleClass('bg-gray');
});
.bg-gray {
background: #eee;
}
这篇关于jQuery不能分配给一个函数结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!