如何动态分配表 ID?

我正在编写一个运行for循环的 PHP 脚本。我在循环内创建多个表,我想根据循环动态命名这些表。


我已经尝试了以下代码,但它不起作用:


<table id="gameweek_history<? echo $i; ?>">

<script>function doCSV<? echo $i; ?>() {

    var table1 = document.getElementById("gameweek_history<? echo $i; ?>").innerHTML;

<button onclick="doCSV(<? echo $i; ?>)">Export HTML Table To CSV File</button>

你能向我解释一下我需要改变什么吗?


至尊宝的传说
浏览 135回答 2
2回答

拉风的咖菲猫

<?php$count = 3;for($i=0; $i<$count; $i++) {?>&nbsp; &nbsp; <table id ="gameweek_history<?php echo $i; ?>">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <script>function doCSV<?php echo $i; ?>() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var table1 = document.getElementById("gameweek_history<?php echo $i; ?>").innerHTML;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <button onclick="doCSV(<?php echo $i; ?>)">Export HTML Table To CSV File</button>&nbsp; &nbsp; </table><?php}?>给出输出:<table id ="gameweek_history0">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <script>function doCSV0() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var table1 = document.getElementById("gameweek_history0").innerHTML;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <button onclick="doCSV(0)">Export HTML Table To CSV File</button>&nbsp; &nbsp; </table>&nbsp; &nbsp; <table id ="gameweek_history1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <script>function doCSV1() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var table1 = document.getElementById("gameweek_history1").innerHTML;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <button onclick="doCSV(1)">Export HTML Table To CSV File</button>&nbsp; &nbsp; </table>&nbsp; &nbsp; <table id ="gameweek_history2">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <script>function doCSV2() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var table1 = document.getElementById("gameweek_history2").innerHTML;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <button onclick="doCSV(2)">Export HTML Table To CSV File</button>&nbsp; &nbsp; </table>

肥皂起泡泡

您应该从您的 javascript 中删除 PHP 代码。这样写:<script>function doCSV(i) {&nbsp; &nbsp;var table1 = document.getElementById("gameweek_history"+i).innerHTML;&nbsp; &nbsp;// do something here with table1</script><table id ="gameweek_history<? echo $i; ?>"><button onclick="doCSV(<? echo $i; ?>)">Export HTML Table To CSV File</button>
打开App,查看更多内容
随时随地看视频慕课网APP