JQuery循环遍历表

时间:2015-04-15 07:44:36

标签: jquery

我有一张桌子:

<table class="table table-striped">
    <thead>
        <tr>
            <th>Music</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><a href="http://www.domin.com/link1.mp3">link1</a></td>  
        </tr>
        <tr>
            <td><a href="http://www.domin.com/link2.mp3">link2</a></td>
        </tr>
        <tr>
            <td><a href="http://www.domin.com/link3.mp3">link3</a></td>
        </tr>
    </tbody>
</table>

我还有两个按钮,nextprev

<button id="prev">Previous</button>
<button id="next">Next</button>

我希望每次点击next或prev按钮将class play设置为活动行并获取play mp3 url并通过此函数设置为jplayer:

$('.play')(function() {
    var url = $(this).attr('href');  
    $("#jquery_jplayer_1").jPlayer("setMedia", {
        mp3: url
    }).jPlayer("play");
    return false;  
});

1 个答案:

答案 0 :(得分:2)

我已将课程play添加到其中一个a 在表中。 Next从第一行开始。 Prev从最后一行开始。 然后,如果它们到达顶部/底部,则移动行并循环。

JSFiddle Demo

$('#next').click(function () {
    if ($('table td a.play').length > 0 && $('table td a.play').parents('tr').next().length > 0) {
        $('table td a.play').removeClass('play').parents('tr').next().find('a').addClass('play');
    } else {
        $('table td a.play').removeClass('play');
        $('table td').first().find('a').addClass('play');
    }
});

$('#prev').click(function () {
    if ($('table td a.play').length > 0 && $('table td a.play').parents('tr').prev().length > 0) {
        $('table td a.play').removeClass('play').parents('tr').prev().find('a').addClass('play');
    } else {
        $('table td a.play').removeClass('play');
        $('table td').last().find('a').addClass('play');
    }
});