我正在尝试掌握 jQuery 的窍门,但我有一段简单的代码无法工作。有人知道为什么这可能不起作用吗?
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("div").live("click", divclicked);
});
function divclicked()
{
if($(this).css("background-color") == "lightblue")
$(this).css("background-color", "red");
}
</script>
<style type="text/css">
div
{
background-color: lightblue;
}
</style>
</head>
<body>
<div id="testdiv">
this is a test
</div>
</body>
</html>
预先感谢您的任何意见。
更新: 下面的解决方案使用“backgroundColor”而不是“background-color”,当样式内联时有效,而不是在使用样式表时有效。
I have updated the example to use a stylesheet.
最佳答案
尝试在脚本中将 background-color
更改为 backgroundColor
:
if($(this).css("backgroundColor") == "lightblue")
$(this).css("backgroundColor", "red");
DOM 倾向于避免使用短划线名称,因为它们不是有效的 JavaScript 标识符。
<小时/>啊啊!当我输入评论时,保罗删除了他的答案...我没有意识到将“背景颜色”传递给 .css()
会做任何事情很有用,更不用说返回实际的 RGB 值了!在您的情况下,效果是相同的(因为您的逻辑需要准确保留原始值),但仍然值得注意以供将来引用。
另外:如果您使用 CSS 类,而不是依赖于直接读取和写入样式,那么您将获得更轻松的时间 - jQuery 与 CSS 类配合得非常好,为 check 提供了简单的方法。 , toggle ,和 modify他们。
关于jquery - 为什么这个 jQuery 代码无法在 Firefox 中改变背景颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/799845/