首页 > 解决方案 > 使用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 代码,而不添加新类?

标签: javascriptjqueryhtml

解决方案


你有点过于复杂了。您只需使用 切换相关类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
  });
});

推荐阅读