-1

我想要多个 span.play 没有 ID,可以点击并播放一些音频文件。

问题:仅在当前文件 $(this) 上显示持续时间

$('.play').each(function() {

    $(this).append('<span class="playIcon"><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/7/76/Fairytale_player_play.png/14px-Fairytale_player_play.png"></span><span class="playDur"></span>');


    $(this).click(function() {
        var file = this.firstChild;
        if (file.paused != false) {
            //+ stop all others before playing new one
            file.play();
        } else {
            file.pause();
        }
        file.addEventListener("timeupdate", function() {
            var len = file.duration,
                ct = file.currentTime,
                s = parseInt(ct % 60),
                m = parseInt((ct / 60) % 60);
            if (s < 10) {
                s = '0' + s;
            }
            $(".playDur").html('&nbsp;(' + m + ':' + s + ')');
            if (ct == len) {
                $(".playDur").html('');
            }
        }, false);
    });

});

测试:

http://jsfiddle.net/sQPPP/

http://jsfiddle.net/sQPPP/1/ - 使用$(this).children( ".foo" )

4

1 回答 1

0

您需要将.playjQuery 对象保存在一个变量中,作为回调中的this更改。addEventListener

http://jsfiddle.net/sQPPP/2/

$('.play').each(function(index) {
    var $play = $(this);
    $play.append('<span class="playIcon"><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/7/76/Fairytale_player_play.png/14px-Fairytale_player_play.png"></span><span class="playDur"></span>');


    $play.click(function() {
        var file = this.firstChild;
        if (file.paused != false) {
            //+ stop all others before playing new one
            file.play();
        } else {
            file.pause();
        }
        file.addEventListener("timeupdate", function() {
            var len = file.duration,
                ct = file.currentTime,
                s = parseInt(ct % 60),
                m = parseInt((ct / 60) % 60);
            if (s < 10) {
                s = '0' + s;
            }
            $play.children( ".playDur" ).html('&nbsp;(' + m + ':' + s + ')');
            if (ct == len) {
                 $play.children( ".playDur" ).html('');
            }
        }, false);
    });

});​
于 2012-12-15T20:19:13.677 回答