Jquery 基于 class 事件的悬停选择器不起作用

Jquery on and hover selector based on class events not working

$(".typeofcontent").on({

    $(".typeofcontent").hover(function() {
        $(this).css("color", "#f9d58e");    
    });

}

此 jQuery 代码不执行设置类名为 typeofcontent 的元素的 CSS 颜色的命令。相反,它不会给出控制台错误代码,也不会执行。你介意解释一下我做错了什么吗?

只需要下面的代码。由于 hover 事件由 hover() 绑定,您不需要 on.

$(".typeofcontent").hover(function() {
    $(this).css("color", "#f9d58e");
});

更好的方法

您不需要 Javascript 来执行此操作。 使用CSS

.typeofcontent:hover {
    color: #f9d58e;
} 
jQuery(document).ready(function() {
    $(".typeofcontent").hover(function() {
        $(this).css("color", "#f9d58e");
    });
});

您传递的对象不是 on() 的有效重载。如果你想使用 on() 传入 event, selector(for delegation ), 和 回调

$(document).on('hover','.typeofcontent', function(){
    $(this).css("color", "#f9d58e");
});

jquery.on 函数的一般语法是.on("event","child selectors","data","event handler")。 第二个和第三个参数是可选的,因此您可以跳过它们。

在您的情况下,"event"在此处输入代码作为无效对象传递。 所以正确的用法是

$(".typeofcontent").on("hover", function() {
    $(this).css("color", "#f9d58e");
});
$(".typeofcontent").hover(function(){
    $(this).css("color", "#f9d58e");
}); 

如果您想使用悬停功能,以上代码足以完成工作。但是,如果你想用 "on" 来做,代码片段是:

$(".typeofcontent").on('mouseover',function(){
    $(this).css("color", "#f9d58e");
}); 
$(".typeofcontent").hover(function() {
    $(this).css("color", "#f9d58e");
});

这会起作用