简体   繁体   中英

jQuery Trigger Click not work at first click

I have a trouble with jquery trigger click. I need to play audio from audio tag via trigger click. When i click first time on first element it work, but if I click in another element, the first click not work. If i click 2nd time it will be work.

  var Audioplaying = false;
  jQuery('.playAudio').click(function(e) {

        var playerID = jQuery(this).next('.audioPlayer').attr('id');
        var playerBTN = jQuery(this);

        if (Audioplaying == false) {
            Audioplaying = true;
            jQuery("#"+playerID)[0].play();
            playerBTN.addClass('play');
        } else {
            Audioplaying = false;
            jQuery("#"+playerID)[0].pause();
            playerBTN.removeClass('play');
        }
        e.preventDefault();
  });

The variable Audioplaying is shared, it is not unique so you probably want it to be unique per element. So use data() to keep track of the state for each player.

jQuery('.playAudio').click(function(e) {

    var player = jQuery(this).next('.audioPlayer');
    var playerID = player.attr('id');
    var playerState = player.data('isPlaying') || false; // get if it is running
    player.data('isPlaying', !playerState);  // update the boolean
    var playerBTN = jQuery(this);

    if (!playerState) {
        jQuery("#"+playerID)[0].play();
        playerBTN.addClass('play');
    } else {
        jQuery("#"+playerID)[0].pause();
        playerBTN.removeClass('play');
    }
    e.preventDefault();
});

Maintain the state of each button separately. so, you can use an object with it's 'id' as the key.

example : { button_id : true/false }

  var Audioplaying = {};
  jQuery('.playAudio').click(function(e) {

        var playerID = jQuery(this).next('.audioPlayer').attr('id');
        var playerBTN = jQuery(this);

        if (!Audioplaying[playerID]) {
            Audioplaying[playerID] = true; // every button has it's own state maintained in the object.
            jQuery("#"+playerID)[0].play();
            playerBTN.addClass('play');
        } else {
            Audioplaying[playerID] = false;
            jQuery("#"+playerID)[0].pause();
            playerBTN.removeClass('play');
        }
        e.preventDefault();

  });

Hope it helps you arrive at a optimal solution.

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