javascript变量中的autoincrement id

时间:2013-10-03 08:22:23

标签: javascript php

在我的while(row)语句中为新ID分配值时没有取得任何成功: 这是一个简单的例子,希望你明白我想做什么。感谢

<?php...

$id=0;
while(rows = mysql_fetch_data){
$id = $id + 1;

$teamname = rows['team'];
?>    

<script>
var team = '<?php echo $teamname; ?>';
var id = 'id_<?php echo $id; ?>';   

//Here I want to save the teamnames as javascript variable "id_1", "id_2" etc, which I can use outside the while statement. 

//For each row id = id_1, id_2, id_3, id_4.
//I want to make id_1 a variable which outputs teamname
//So that 
//var id_1 = team; //team 1
//var id_2 = team; //team 2


<?php    
}
?>

var id_1;
var id_2;
document.write("Teamname 1 = " + id_1 + "</br> Teamname 2 = " + id_2); //Here I want output of teamname 1 and 2.
</script>

2 个答案:

答案 0 :(得分:2)

我建议使用数组而不是单个变量,因为你有一个团队名称列表:

<?php

$teamnames = [];
while(rows = mysql_fetch_data){

  $teamnames[] = rows['team'];
}
?>    
<script>
var teamnames = <?php echo json_encode($teamnames); ?>;
</script>

然后您最终获得了一个客户端JavaScript团队名称数组。当你可以然后用document.write输出它们时,可能有更好的选择。

但是这是你的document.write更新后使用数组:

var n;
for (n = 0; n < teamnames.length; ++n)
{
  // Note: There's almost certainly a better choice than `document.write`
  document.write("Teamname " + (n + 1) + " = " + teamnames[n] + "</br>");
}

答案 1 :(得分:0)

用以下内容替换您的代码 应该为您提供您之后的输出...

<script>

<?php
//...

$id_counter = 1;   //Initialise counter
while($row = mysql_fetch_assoc()){
    echo 'var id_'.$id_counter.' = "'.$rows['team'].'";'; //Echo row in the format: var id_X = "team_name";
    $id_counter++; //Increment the counter
}

?>

document.write("Teamname 1 = " + id_1 + "</br> Teamname 2 = " + id_2); //Here I want output of teamname 1 and 2.
</script>