简体   繁体   English

jQuery触发器单击在第一次单击时不起作用

[英]jQuery Trigger Click not work at first click

I have a trouble with jquery trigger click. 我在使用jquery触发单击时遇到麻烦。 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. 变量Audioplaying是共享的,它不是唯一的,因此您可能希望每个元素唯一。 So use data() to keep track of the state for each player. 因此,请使用data()跟踪每个玩家的状态。

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. 因此,您可以使用带有“ id”作为键的对象。

example : { button_id : true/false } 例如:{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. 希望它可以帮助您找到最佳解决方案。

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

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