代码之家  ›  专栏  ›  技术社区  ›  Razvan Cuceu

如果类存在,则setinterval播放声音

  •  1
  • Razvan Cuceu  · 技术社区  · 7 年前

    我制作了这个片段,如果在div中有一个类为“card new order”的元素,应该在这里搜索

    ID为“comenzi”的div每5秒刷新一次,并更新里面的卡和它们的类。

    如果找到带有类的卡,则播放声音,直到脚本找不到该元素为止。

    这是我的代码,但不知怎么搞不好。

    var audio = document.getElementById("ring");
    setInterval(function(){ 
        $('#comenzi').load(document.URL +  ' #comenzi'); 
        $('.contents > .card').each(function(i) {
            if($(this).hasClass('card-new-order')){
                audio.play();
            }else{
                audio.pause();
            }
        });
    
    }, 5000);
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Dacre Denny    7 年前

    看起来您正在尝试在 load() 方法已完成。

    考虑修改代码,以便在 加载() 操作可用。你可以利用 the success callback 加载() 方法:

    var audio = document.getElementById("ring");
    function refresh(){ 
    
        // Pass a success callback function to load() which is run after
        // the load has succeeded. Also, remove the whitespace before #comenzi
        $('#comenzi').load(document.URL +  '#comenzi', function() {
    
        // The loaded content from document.URL#comenzi have loaded and
        // can now be accessed
        $('.contents > .card').each(function(i) {
    
            if($(this).hasClass('card-new-order')){
                audio.play();
            } else {
                audio.pause();
            }
        });
    
        // Start the next cycle after the contents have loaded
        setTimeout(refresh, 5000)
        });     
    }
    
    // Start the refresh cycle
    refresh();
    

    上面显示的另一个建议是使用 setTimeout 而不是 setInterval 以确保下一次刷新发生在从 加载() . 这个 设定间隔 基于方法的方法会冒着一次执行refresh()调用的风险(如果服务器将内容返回到 #comenzi 反应时间超过5秒等)

    希望这有帮助!