我正在尝试切换 div 元素的背景颜色,但我的代码不起作用。我编写了以下代码:
$(document).ready(function(){
var $on_off = true;
$('div.hot').on('click', function($on_off){
if($on_off){
$(this).css('background-color', 'red');
}
else{
$(this).css('background-color', 'yellow');
}
$on_off = !$on_off;
});
});
我不明白为什么这行不通。 谢谢!
最佳答案
Remove argument from
on
handler as first argument isevent-object
which is always evaluated astrue
(Boolean({})===true
)
$(document).ready(function() {
var $on_off = true;
$('div.hot').on('click', function() {
if ($on_off) {
$(this).css('background-color', 'red');
} else {
$(this).css('background-color', 'yellow');
}
$on_off = !$on_off;
});
});
简化代码:
$(document).ready(function() {
var $on_off = true;
$('div.hot').on('click', function() {
$(this).css('background-color', $on_off ? 'red' : 'yellow');
$on_off = !$on_off;
});
});
关于javascript - 如何使用 jQuery 切换 div 元素的背景颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37651380/