【问题标题】:each() iteration in conjuction with trigger与触发器结合使用的 each() 迭代
【发布时间】:2015-10-22 16:43:23
【问题描述】:

我有这个代码:

function gamePlay(array){
    $.each(array, function(index, value){
        $("." + sounds[value]).trigger("play");
    });
}

函数获取一个带有值(类名)的数组。我想在数组的每次迭代中播放声音。但是,相反,我会同时播放所有声音。我试过使用 setTimeout 但它又做了同样的事情。我需要一些可以停止/暂停迭代直到触发声音完成的东西。

【问题讨论】:

  • 声音的持续时间是多少?
  • 最好先挂钩ended 事件,然后再挂钩play 下一个audio 元素。如果您可以在问题中添加 HTML 示例,我可以举一个示例说明如何执行此操作。
  • @Azzi 他们可能是 1/25 秒......只是哔声。

标签: javascript jquery triggers each


【解决方案1】:

您可以像这样设置超时功能。假设所有声音片段具有相同的持续时间。

function gamePlay(array){

    var duration = 1000;  //1000ms

    $.each(array, function(index, value){
        (function(value, index){

           setTimeout(function(){

              $("." + sounds[value]).trigger("play");

            }, index * duration);

        })(value, index);      
    }
}

【讨论】:

  • @theo 不,它没有。这使得每个声音都是 1 秒长的假设完全无效。
  • @Tomalak 我的声音是哔哔声,不到一秒钟,所以这不是假设。此外,代码也可以在没有内部函数的情况下工作,我刚刚尝试了它们。所以我删除了内部函数
【解决方案2】:

试试这样的:-

function gamePlay(array){
    playSound(array, 0);
}

function playSound(array, index){
    if((index+1) < array.length){
        $("." + sounds[array[index]]).on('ended', function() { 
            playSound(array, ++index);
        });
    }
    $("." + sounds[array[index]]).trigger("play");
}

这是未经测试的,但给出了如何在上一个声音完成后触发下一个声音的想法。

【讨论】:

    猜你喜欢
    • 2015-05-21
    • 2013-10-24
    • 2019-07-21
    • 2017-02-25
    • 1970-01-01
    • 2019-03-29
    • 2012-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多