php - 循环遍历 jQuery 语句

标签 php javascript jquery mysql

我正在使用一个数据库中的一个字段来存储歌曲位置...当我在数据库中有一首歌曲时,它在单击时播放得很好。但是,如果数据库中有 2 首或更多首歌曲,则在单击时它们都会同步播放。如何循环 jQuery 附加语句以像 PHP while 循环一样工作?抱歉,我还在学习 jQuery/Javascript...我实际上遇到了这个问题。所以一个解决方案确实会对我有帮助!

<script src="http://code.jquery.com/jquery-latest.js"></script>
<?php
mysql_connect("localhost", "root", "")or die("Could not connect: " . mysql_error());
mysql_select_db("kevin") or die(mysql_error());

$song_query = mysql_query("SELECT idsongs, songuri, songname FROM songs");

    while($row = mysql_fetch_array($song_query)) {
    echo "<span class='song'><b>Song Name: </b>";
    echo $row['songname'];
    echo "<br>";
    //echo '<img alt="" id="play" src="play.png" />';
    //echo '<div id="audio"></div>';
?>
<script type="text/javascript">
$(document).ready(function() {
 $('#play').click(function() {
        $("#audio").append('<audio autoplay="true" src="<?php echo $row['songuri'] ?>" /></audio>');
});
});
</script>
<img alt="" id="play" src="play.png" />
<div id="audio"></div>
<?php } ?>

最佳答案

这为您的所有歌曲提供了自己的停止/播放控件。

<script src="http://code.jquery.com/jquery-latest.js"></script>
<?php
mysql_connect("localhost", "root", "")or die("Could not connect: " . mysql_error());
mysql_select_db("kevin") or die(mysql_error());

$song_query = mysql_query("SELECT idsongs, songuri, songname FROM songs");

while($row = mysql_fetch_array($song_query)) {
    echo "<div class='song' sid='".$row['idsongs']."' songuri='".$row['songuri']."'>";
        echo "<b>Song Name: </b>";
        echo $row['songname'];
        echo "<br>";
        echo "<img class='play' src='play.png' /><br>";
        echo "<div class='audio'></div>";
        echo "<div class='stop'>Stop!</div>";
    echo "</div>";
} 
?>


<script type="text/javascript">
$(document).ready(function() {
    $('.play').click(function() {

        var songdiv = $(this).parent('div.song');

        var songuri = songdiv.attr('songuri');      
        var sid = songdiv.attr('sid');
        // stop this song if it's already playing

        stopPlayer(sid);

        // play
        var audio = '<audio class="player" sid="'+sid+'" autoplay="true" src="'+songuri+'" /></audio>';
        $(this).siblings('div.audio').html(audio);
    });
    $('.stop').click(function(){
        var songuri = $(this).parent('div.song').attr('sid');
        stopPlayer(songuri);
    });
});

function stopPlayer(id) {
    var p = $('.player[sid='+id+']');
    if (p[0]) {
        p[0].pause();
    }


}

</script>

关于php - 循环遍历 jQuery 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7863547/

相关文章:

javascript - 页面加载时如何在jquery中获取增量值

javascript - JSON数据存入表需要tr元素

javascript - 如何使用ajax在不刷新页面的情况下从数据库中检索数据

php - 可以使用 switch 语句比较 PHP 中的字符串吗?

javascript - 从javascript数组中删除逗号

javascript - Angular 4 图像 slider

javascript - 使用 php/jquery 动态更新单个模态

php - 通过 PHP/Javascript 登录 Wordpress

javascript - 如何让javascript slider 自动滑动

javascript - Bootstrap Popover with textarea重置文本值