简体   繁体   English

切换字体真棒图标

[英]Toggling Font Awesome Icons

Right now, the button has an arrow icon.现在,该按钮有一个箭头图标。 When onclick is triggered, it switches to the "x" icon, but then I click it again, nothing happens.当 onclick 被触发时,它切换到“x”图标,但是我再次单击它,没有任何反应。 Can anybody tell me what I can do to get it back to the original (arrows) icon when I click on it again?谁能告诉我当我再次点击它时我能做些什么让它回到原来的(箭头)图标? Below is my code.下面是我的代码。

<button class="button" data-toggle="tooltip" title="Like"><i class="fa fa-arrows-alt"></i></button>


<script>
    $("button").click(function(){
    $(this).find("i").removeClass("fa fa-arrows-alt").addClass("fa fa-close");
});
</script>

Looks like your click function is only handling one-way toggle.看起来您的点击 function 仅处理单向切换。 Perhaps check for the current state first and then process the state-change based on that?也许先检查当前的 state 然后根据它处理状态更改?

<script>
    $("button").click(function(){
        // First, check for current state
        if ($(this).find("i").hasClass("fa-arrows-alt")) {
            // Handle "has class fa-arrows-alt"
            $(this).find("i").removeClass("fa-arrows-alt").addClass("fa-close");
        } else {
            // Handle "does not have class fa-arrows-alt"
            $(this).find("i").removeClass("fa-close").addClass("fa-arrows-alt");
        }
    });
</script>

Your action is always "remove arrow class, add close icon class".您的操作始终是“删除箭头 class,添加关闭图标类”。 You should detect the current class of the button, and then apply a specific action according to this.您应该检测按钮的当前class,然后根据此应用特定动作。 For example, you can modify your code like this:例如,您可以像这样修改代码:

$("button").click(function() {
    if ($(this).find("i").hasClass("fa-arrows-alt")) {
        $(this).find("i").removeClass("fa-arrows-alt").addClass("fa-close");
    } else if ($(this).find("i").hasClass("fa-close")) {
        $(this).find("i").removeClass("fa-close").addClass("fa-arrows-alt");
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM