Javascript 为什么这个if语句不起作用?

Javascript 为什么这个if语句不起作用?,javascript,jquery,html,audio,Javascript,Jquery,Html,Audio,我有一些div,我使用jQuery的淡入/淡出功能在点击链接时将其带到页面上。每个页面都有一个关联的html5音频元素,该元素也会相应地淡入/淡出 $('.link').on('click', function(e){ var targetpage = $($(this).attr("href")); $('.pagecontainer>div').fadeOut(0); //fade out currently displayed page targetpage.

我有一些div,我使用jQuery的淡入/淡出功能在点击链接时将其带到页面上。每个页面都有一个关联的html5音频元素,该元素也会相应地淡入/淡出

$('.link').on('click', function(e){
    var targetpage = $($(this).attr("href"));
    $('.pagecontainer>div').fadeOut(0); //fade out currently displayed page
    targetpage.fadeIn(); //fade in page associated with link
    if (targetpage.children().hasClass('backgroundmusic')) {
        $('audio').animate({volume: 0}, 1000); //fade out currently playing audio
        alert('audio faded out');
        $.each($('audio'), function () { //stop all audio
            this.currentTime=0;
            this.pause();
            alert('audio stopped');
        });
        alert('stop function executed');
    }
});

$('.sound').on('play', function () { //since volume was faded out, reset volume when click play button
    $('audio').animate({volume: 1}, 100);
});
HTML:


//所有三个音频元素都位于完全相同的位置
//单击页面链接在当前音频中淡出,在新音频中淡出
“alert('audio Fasted out')”将执行,但“alert('audio stopped')”不会执行,因为它没有运行“$”。每个($('audio'),函数”脚本都不会执行,“alert('stop function executed')”。我必须将这个“each”脚本用作$('audio')。currentTime=0不起作用,美元('audio')。pause(),因为我的页面上有多个音频实例

有人知道为什么这不起作用吗


谢谢。

您将
e
传递给您的函数,但不使用它。可能希望阻止该单击事件的默认操作

e.preventDefault(); //Put this at the top of the callback
这应该可以解决你的.each()问题。此外,你应该使用控制台而不是警报,以免冻结你的页面

console.log('audio faded out'); //Use console instead of alerts
$('audio').each(function () { //Do it this way.
    this.currentTime=0;
    this.pause();
    console.log('audio stopped');
});
console.log('stop function executed');

谢谢,但这不起作用。我发现只有第1页上的音频才能正确停止。第2页和第3页似乎与该脚本不起作用。有人告诉我这可能与您无法停止/暂停/重置尚未加载的音频有关,出于某种原因,DOM中最先出现的音频元素都会加载…仍在寻找修复方法r这个。我不能让它们全部自动加载(即,删除
preload=“auto”
),这将导致google Chrome挂起,因为我的网站上有20个mp3/ogg试图同时加载。您可以将它们设置为在队列中加载。如果您将AJAX之类的东西与jQuery的内置队列一起使用,您可以异步加载所有这些内容-一次加载一个。没有挂起,只是砰的一声。
console.log('audio faded out'); //Use console instead of alerts
$('audio').each(function () { //Do it this way.
    this.currentTime=0;
    this.pause();
    console.log('audio stopped');
});
console.log('stop function executed');