简体   繁体   中英

Using javascript to dynamically toggle FA icons doesn't return original icon

I have a button which looks like this:

<button class="btn btn-sm btn-xs-block btn-success" :data-lane-id="items[0].lane.id" type="button" v-on:click="callNextCustomer(items[0].lane.id)" :class="hasMorePeople(items)">Next Customer <i class="fas fa-bell"></i></button>

When the button has been pressed, callNextCustomer function runs the following:

const spinnerIcon = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>';
var button = document.querySelectorAll('button[data-lane-id="'+lane_id+'"]')
button[0].disabled = true;
button[0].innerHTML = 'Next Customer ' + spinnerIcon;
// run external request using promise
// when complete run the following
button[0].disabled = false;
button[0].innerHTML = 'Next Customer <i class="fas fa-bell"></i>';

When the code is executed, the text changes as expected but the icon doesn't display. Using Google Dev Inspector I can see the icon mark up is present.

在此处输入图像描述

Can anyone explain why this isn't being displayed? I am using Font Awesome v5, I load both the CSS and JS into my page , I load the following JS:

<script data-search-pseudo-elements defer src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/js/all.min.js" crossorigin="anonymous"></script>

IIRC , this is because with font awesome 5, all icons are loaded in on page load. Because you are editing the innerHTML after the fact, the "JS" part of the font awesome scripts you added isn't firing again to update with the fa-bell icon.

What if you load both icons and put the hidden class on the other one and toggle both icon classes hidden when button is clicked?

<button class="btn btn-sm btn-xs-block btn-success" :data-lane-id="items[0].lane.id" type="button" v-on:click="callNextCustomer(items[0].lane.id)" :class="hasMorePeople(items)">
Next Customer 
<span class="icon hidden spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
<i class="icon fas fa-bell"></i>
</button>
.icon.hidden  {
   display: none;
}

When button is clicked you just execute $.jquery command that will toggle the class of.icon as hidden, each click their class will switch hidden.

1st click the < span class="icon spinner-border spinner-border-sm" role="status" aria-hidden="true"> hidden class removed

and the < i class="icon hidden fas fa-bell"> hidden class added.

2nd click vice versa.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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