您如何创建函数来打印在PHP循环内调用的HTML?

时间:2018-12-24 11:56:50

标签: javascript php html

我有一组在用户播放时存储在数组中的剧集。 用户在屏幕上有一块板,我想在该板上打印他/她所做的剧本(单词)。 我尝试传递给数组,然后在无法正常工作的html中打印,所以我问一位老师,我该怎么做。

他告诉我创建一个函数来输出输出和html(我以前从未做过这种类型的函数),其中数组$row(或任何其他名称)在内部传递给该函数,然后我应该在循环内部调用函数,在循环中将数组$row作为参数传递。

我试图做他告诉我的事情,所以我做了以下事情:

PHP

$sqlplays="Select word from plays where usertype=2 and idgame=$idgame";
$result=mysqli_query($link, $sqlplays);


for($i=0;$i<10 && ($row=mysqli_fetch_assoc($result)) ;$i++){
   print($row);

  //rest of the code
}

Java脚本

 <script>
 function print(row){
     var aword=[];
      aword=jogadas;

    for (var i = 1; i <= 10 ;){
        $('.word').append(aword[i]).show();
    }   
}
</script>

HTML

   <div id="row" class="esq">
        <span class="attempt">1 :</span>
        <span class="word"> //Where it should print </span>
    </div> 

当用户第一次播放时,页面显示错误消息:“`错误:在(...)中调用未定义的函数print()“

我不明白为什么会这样,有人可以告诉我这是什么问题吗?而且,如果您能告诉我该功能是否正确打印,我以前从未做过打印html的功能。

谢谢。

1 个答案:

答案 0 :(得分:0)

您可以尝试以此来了解逻辑。

<?php

$sqlplays="SELECT word FROM plays WHERE usertype=2 AND idgame=$idgame";
$result=mysqli_query($link, $sqlplays);
$output = "";

//define function here, it appends each word to the output variable
function printword($w){
    $output .= "<span class='attempt'>1 :</span><span class='word'>".$w."</span><br>";
}

// with while & for loop iterate through 10 elements to repeat the function which appends to $output.
while($row=mysqli_fetch_assoc($result)) {
  for($i=0;$i<10;$i++){
     printword($row['word']);
    //rest of the code
  }
}


?>
<!-- HTML to print the output -->
   <div id="row" class="esq">
        <?php echo $output; ?>
    </div>