如何在带有空格的类中使用jquery选择器?



我有下面的 Html 代码:

<span class="fa fa-heart-o"></span> 

我想在此类的所有跨度中切换class="fa fa-heart-o"class="fa fa-heart"悬停

$("span").filter(".fa.fa-heart-o").hover(function () {
alert("hola");
this.removeClass('fa fa-heart-o');
this.addClass('fa fa-heart');
}, function () {
alert("adios");
this.removeClass('fa fa-heart');
this.addClass('fa fa-heart-o');
});

}(;

我已经尝试了很多方法,但没有任何效果。

问题是你试图在 DOM 对象上调用 jQuery 方法。

与其将 DOM 对象this作为目标,不如将.removeClass()链接并.addClass()jQuery 包装器$(this)

$("span").filter(".fa.fa-heart-o").hover(function() {
//alert("hola");
$(this).removeClass('fa fa-heart-o');
$(this).addClass('fa fa-heart');
}, function() {
//alert("adios");
$(this).removeClass('fa fa-heart');
$(this).addClass('fa fa-heart-o');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<span class="fa fa-heart-o"></span>

与其删除和添加一个类attr()我们可以简单地使用 jQuery 的函数将类更改为所需的类,如下所示

$("span").filter(".fa.fa-heart-o").hover(function() {
$(this).attr('class', 'fa fa-heart');
}, function() {
$(this).attr('class', 'fa fa-heart-o');
});

最新更新