jQuery播放列表函数错误:函数未定义

jQuery playlist function error: function undefined

本文关键字:函数 未定义 错误 jQuery 播放列表      更新时间:2023-09-26

我试图创建一个.mp3播放器只是通过音轨循环,但我一直在Firebug上得到错误,我使用的主要功能是未定义的,虽然我定义它。下面是代码:

$(document).ready(function() {
var counter=1;
var nextSong = function(){
    if (counter <= 3) {
        $('audio').src="audio/audio"+counter+".ogg";
        $this.load();
        $this.play();
        counter++;
    }
    else {
        counter=0;
        $('audio').src="audio/audio"+counter+".ogg";
        $this.load();
        $this.play();
    };
  };
});

我的标记是:

<!DOCTYPE html>
    <head>
        <title>Dokimastiko Audio Player</title>
        <script type="text/javascript" src="js/jquery.min.js"></script>
        <script type="text/javascript" src="js/dokimastiko.js"></script>
    </head>
    <body>
        <audio src="audio/audio1.ogg" controls autoplay onended="nextSong();"></audio>
    </body>

任何想法吗?

我考虑过是否要给你上一堂完整的课,告诉你为什么你的代码很糟糕…既然我现在手头上的工作不多,我就这么做吧……: P

首先这里的$this是未定义的,所以在它上面调用方法显然也是未定义的。

你可能从某个地方复制了代码,这很好,但你需要能够聪明地复制,而不是盲目地复制。

…你改变了你的代码中途我的帖子,所以更新:$(this)$(document)相同,因为这是$(document).ready(function() {})this的上下文

所以,不,还是错的。

第一个修改应该是:

$('audio').load();
$('audio').play();

但实际上这仍然是错误的。因为$('audio')是一个jquery对象,并且它不直接包含DOM级方法loadplay,所以您需要获取DOM对象:

$('audio').get(0).load();
$('audio').get(0).play();

现在你会想知道为什么.get(0),这是因为$('audio')是所有与'audio'匹配的集合,所以get(0)只返回第一个。

如果你决定在页面上添加更多的audio标签,这很容易损坏,所以你应该给音频标签一个唯一的标识符:

<audio src="audio/audio1.ogg" controls autoplay onended="nextSong();" id="audio1"></audio>

然后在jquery选择器中使用id:

$('#audio1').get(0).load();
$('#audio1').get(0).play();

这仍然有点冗长,但是考虑到您只需要这样做,这是最简单的方法。

更新:

根据@JanDvorak的建议,这里有一个使用jquery事件的例子

小提琴:http://jsfiddle.net/MpBP5/1/

jQuery(document).ready( function($) {
    $('#audio1').bind('ended', function(e) {
        alert('end');
    });
});

我也可以继续这个"教训",你应该尽量不要抽象地定义你的音乐url,如果有人只是离开你的页面,它击中了一个文件,对于计数器#,不存在?

我将声明一个你想要加载的文件数组:

var library = [
    'http://www.archive.org/download/bolero_69/Bolero.mp3',
    'http://www.archive.org/download/MoonlightSonata_755/Beethoven-MoonlightSonata.mp3',
    'http://www.archive.org/download/CanonInD_261/CanoninD.mp3',
    'http://www.archive.org/download/PatrikbkarlChamberSymph/PatrikbkarlChamberSymph_vbr_mp3.zip'
];
var currentIndex = 0;

然后循环遍历列表:

jQuery(document).ready( function($) {
    $('#audio1').bind('ended', function(e) {
        currentIndex++;
        if (currentIndex > library.length-1) {
            currentIndex = 0;
        }
        this.src = library[currentIndex];
        $('#url').html(library[currentIndex]);
    });
    $('#audio1').attr('src', library[currentIndex]);
        $('#url').html(library[currentIndex]);
});
http://jsfiddle.net/MpBP5/3/

如果你不想要一个固定的音频文件列表来播放(你确实应该这样做),你可以用至少一些规则来生成数组