简体   繁体   中英

how to change font awesome icon on click

I'm using this script

<audio src="http://193.108.24.21:8000/fresh" id="audio"></audio>
    <i class='fas fa-play fa-5x' id="play" onclick="play(this)"></i>

    <script>
    function play(button) {
    var audio = $(button).prev()[0];
    if (audio.paused) {
        audio.play();
        $('#play').removeClass('fa-play')
        $('#play').addClass('fa-pause')
    }else{
        audio.pause();
        audio.currentTime = 0
        $('#play').addClass('fa-play')
        $('#play').removeClass('fa-pause')
    }
}
    </script>

but when I add several to one page it doesn't work.

image

This is what happens, each player works for itself, but the icons do not. When one player is clicked, only one icon changes as in the picture

image2

How can I make each icon stand out for itself? I changed the id for each one individually but it didn't happen again. Thanks!

Use $(button) instead of $("#play") to target the clicked button instead of an id, which won't work because it's not unique.

    <script>
    function play(button) {
    var audio = $(button).prev()[0];
    if (audio.paused) {
        audio.play();
        $(button).removeClass('fa-play')
        $(button).addClass('fa-pause')
    }else{
        audio.pause();
        audio.currentTime = 0
        $(button).addClass('fa-play')
        $(button).removeClass('fa-pause')
    }
}
    </script>

also you could use.toggleClass('fa-play fa-pause') instead of adding and removing the classes manually.

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