循环数据数组

时间:2017-05-29 09:17:54

标签: javascript php

我正在为我们当地的足球俱乐部建立一个窄播解决方案。在其中一个页面上,我想在没有重新加载的情况下遍历团队。使用数据属性获取团队数据。它看起来像这样:

$teamcode = 'seniors1';
$poulecode = 'A';
$teamdata = '
<div id="teamcontainer">
<div data-param-poulecode="'.$poulecode.'"></div>
<div data-param-teamcode="'.$teamcode.'"></div>
</div>
';
echo $teamdata

有多个团队和多个poules。有没有办法循环遍历一个teamdata数组,每10秒用新的团队变量刷新一次teamcontainer,而无需重新加载页面?

1 个答案:

答案 0 :(得分:0)

您可以使用php将data-param-attributes设置为数据数组。然后使用jquery迭代数据并更改值。这是一个例子:

<?php
// Save codes as array
$teamcode = ['seniors1','seniors2'];
$poulecode = ['A','B'];
$teams = json_encode($teamcode);
$poules = json_encode($poulecode);
?>
<!DOCTYPE html>
<html>
<head>
    <script type= "text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
    <div id="teamcontainer">
        <!--pass variables into data-param attribute-->
        <div id="teams" data-param-teamcode='<?php echo $teams; ?>'></div>
        <div id="poules" data-param-poulecode='<?php echo $poules; ?>'></div>
    </div>
</body>
<script type="text/javascript">
    $(document).ready(function(){
        var teams = $("#teams").data("paramTeamcode"), poules = $("#poules").data("paramPoulecode");
        var activeTeamIndex = 0, activePouleIndex = 0;

        // Switch teams and poles
        var switchTeams = function(activeIndex){
            $("#teams").text(teams[activeIndex]);
        };
        var switchPoules = function(activeIndex){
            $("#poules").text(poules[activeIndex]);
        };

        // Show the first teams and poules
        switchTeams(0);
        switchPoules(0);

        // Switch teams and poles every 10 seconds
        setInterval(function(){
            // Reset indexes if they exceed array length
            if (activePouleIndex > poules.length)
                activePouleIndex = 0;
            if (activeTeamIndex > teams.length)
                activeTeamIndex = 0;
            switchTeams(activeTeamIndex++);
            switchPoules(activePouleIndex++);
        },10000);
    });
</script>
</html>