javascript - 使用jquery更改单击按钮的html代码时遇到问题
问题描述
我在 html 中有一个按钮:
<button class="addbtn"><i class="fas fa-plus-circle"></i></button>
我想在点击时更改按钮的 html 代码(图标)。新的html代码是:
<button class="addbtn"><i class="fas fa-times-circle"></i></button>
每次单击按钮时,我都想切换到另一个图标。所以我使用了这段代码:
$(document).ready(function(){
$(".addbtn").click(function(){
var flag = true ;
if(flag){
$(".addbtn").html("<button class='addbtn'><i class='fas fa-times-circle'></i></button>");
$(".add").animate({height:'500'});
flag = false ;
} else {
$(".addbtn").html("<button class='addbtn'><i class='fas fa-plus-circle'></i></button>");
$(".add").height(60);
flag = true ;
}
});
});
但它不会改变之前的 html 类“addbtn”,它会添加另一个“addbtn”类作为之前类的子类。
如何只更改当前的 html 代码,而不添加新类?
解决方案
你有点过于复杂了。您只需使用 切换相关类toggleClass()
。您不需要重新编写元素的 HTML,也不需要使用任何全局标志。尝试这个:
$(".addbtn").click(function() {
var $el = $(this).find('i').toggleClass('fa-plus-circle fa-times-circle');
$(".add").animate({
height: $el.hasClass('fa-times-circle') ? 500 : 60
});
});
推荐阅读
- visual-studio-code - 为什么 jsconfig.json 文件报告“未找到”问题?
- python - Faker 和熊猫 | ValueError:值的长度 (1) 与索引的长度 (2) 不匹配
- angular - angular subscribe 中的代码不等待 API 响应到来
- javascript - 了解 Javascript 中的代码和关键关键字
- c++ - 带函数调用的最大 C++ 数组
- r - R:PDF 列表中每个信号(元素)的线图
- scp - 当您使用 jupyterhub 连接到一个集群时,您如何使用 scp 将数据传输到另一个 hpc?
- python - 闰年和石斑鱼功能
- c# - 我如何在数据开始到达时立即处理数据 - EntityFramework
- apache - 如何使用 htaccess 将以下 urls 模式重写为特定的 php 文件?