我有一个加号字体超赞图标,我想在用户单击加号时将其更改为减号,反之亦然
我在HTML表中使用它来扩展一些行
$('i').click(function() {
$(this).find('i').toggleClass('fas fa-plus fas fa-minus');
});
.icon {
color: green;
cursor: pointer;
margin-right: 6px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css">
<i class="fas fa-plus icon" data-toggle="collapse" data-target=".row1"></i>
答案 0 :(得分:2)
您快到了,但是选择器不正确(您可以在事件处理程序中使用$(this)
来引用被单击的元素)
$('i').click(function() {
$(this).toggleClass('fa-plus fa-minus');
var color = ($(this).hasClass('fa-minus')) ? 'red' : 'green';
$(this).css('color', color);
});
.icon {
color: green;
cursor: pointer;
margin-right: 6px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css">
<i class="fas fa-plus icon" data-toggle="collapse" data-target=".row1"></i>
答案 1 :(得分:1)
无需使用查找$this
代表i
,并切换多朋友类来更改class
和形状,如下所示。
$('i').click(function() {
$(this).toggleClass('fa-plus green fa-minus red');
});
.icon {
color: green;
cursor: pointer;
margin-right: 6px;
}
.green{
color: green;
}
.red{
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css">
<i class="fas fa-plus icon" data-toggle="collapse" data-target=".row1"></i>
答案 2 :(得分:0)
您必须删除find(),它将起作用。
$('i').click(function() {
$(this).toggleClass('fa-plus fa-minus');
$(this).hasClass('fa-minus')? $(this).css('color','red'): $(this).css('color','green');
});
.icon {
color: green;
cursor: pointer;
margin-right: 6px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css">
<i class="fas fa-plus icon" data-toggle="collapse" data-target=".row1"></i>