在悬停时更改div颜色

hac*_*aut 2 html javascript css jquery

尝试更改每个div的背景颜色,并在鼠标悬停在div上时使其保持这种状态.无法让它改变颜色.我究竟做错了什么?这是小提琴.

$('.container').on('hover', '#gridSquare', function(){
        $(this).css('background-color', 'white');
    });
Run Code Online (Sandbox Code Playgroud)

先感谢您!

Aru*_*hny 9

不需要使用jQuery,只需使用css选择器:悬停

#gridSquare:hover {
    background-color: white;
}
Run Code Online (Sandbox Code Playgroud)

演示:小提琴

如果要使用jQuery,则需要使用mouseenter和mouseleave

$('.container').on('mouseenter', '#gridSquare', function () {
    $(this).css('background-color', 'white');
}).on('mouseleave', '#gridSquare', function () {
    $(this).css('background-color', '');
});
Run Code Online (Sandbox Code Playgroud)

演示:小提琴


更新
如下面评论中所建议的,元素的ID在文档中必须是唯一的,因此使用class而不是id来对相似的元素进行分组.

演示:小提琴