2016-07-01 12 views
0

PHPで結果をエコーアウトしたとき、データベースをループして「エコー」に表示しますが、javascriptを使用して表示しようとすると偶数ループ。何がjavascriptの問題ですか?JavaScriptがPHPループ内で動作しない

<?php 
while($row = $result->fetch()){ 
    $id = $row['id']; 

    echo $id; //loops through and displays the all the id's in order in the database 
    ?> 

    //this only displays the first id and doesn't loop even though it is in the php while loop 
    <script> 
     document.getElementById("test").innerHTML = "<?= $id ?>"; 
    </script> 
    <span id="test"></span> 

    <?php 
} 
?> 
+2

ID年代で試してみてください。それを除けば、あなたはIDでそれを得ることができる前に要素が存在しなければなりません。 – jeroen

+0

@jeroen okですから、getElementByIdとdocument.write以外のjavascriptの変数を "エコー"する方法はありますか? – johnniexo88

+0

私は、なぜHTMLを直接出力するのではなく、JSを導入するのか分かりませんが、なぜPHP出力に値の配列を持たないのかと思ったら、PHPループの後にJS適切なHTML要素を作成する配列内のデータ? – nnnnnn

答えて

1

トンは一意である必要があり、HTMLにこの

<?php 

while($row = $result->fetch()){ 
$id = $row['id']; 

echo $id; //loops through and displays the all the id's in order in the database 
?> 

//this only displays the first id and doesn't loop even though it is in the php while loop 

<!-- change in id name --> 
<span id="test_<?=$id?>"></span> 

<script type="text/javascript"> 
    //change here 
    document.getElementById("test_<?=$id?>").innerHTML = "<?= $id ?>"; 
</script> 
<?php 
    } 
    ?> 
+0

です。ありがとう! – johnniexo88

+0

とにかくこれで関数を呼び出すことができます: "document.getElementById(" test_ ").innerHTML = callJSFunction()"? – johnniexo88

+0

クリックするたびにクリックしてみると、クリックすると呼び出されます。 –

関連する問題