我没有太多使用php和javascript,希望得到一些帮助。我希望能够准确检测单击了哪个按钮。我正在每行创建一个按钮,但我不知道如何弄清楚单击是在哪一行中进行的。这就是我到目前为止所拥有的...
# Get all the table data from the database
$getData = mysqli_query($conn, "SELECT * FROM `query_table`") or die ("Error occured while selecting!");
// echo '<form method="post" action="index.php">';
echo '<table border="1">';
echo '<tr>';
echo '<td>Questions</td>';
echo '<td>Likes</td>';
echo '<td></td>';
echo '</tr>';
# Loop through each row and print out the question
while ($row = mysqli_fetch_array($getData)) {
echo '<tr>';
echo '<td>';
echo $row['Question'];
echo '</td>';
echo '<td>';
echo $row['Likes'];
echo '</td>';
echo '<td>';
?>
<input type="button" id="myButton" value="Like" onclick="myFunc(<?=$row['ID']?>)" />
<?php
echo '</td>';
echo '</tr>';
}
echo '</table>';
// echo '</form>';
echo '<p id="text"></p>';
mysqli_close($conn);
?>
<script type="text/javascript">
function myFunc(id) {
document.getElementById("text").innerHTML = id;
}
</script>
到目前为止,这会打印出单击按钮的行 id,但我认为我不能将该参数值直接分配给 php 变量,然后我可以将其用于 mysql 查询。这样的事情通常是如何完成的,请帮忙。
<input type="button" data-id="<?=$row['ID']?>" value="Like" onclick="myFunc(this)">
和
<script type="text/javascript">
function myFunc(button) {
document.getElementById("text").innerHTML = button.getAttribute('data-id');
}
</script>
在 JavaScript 中,标记"this"是指代码运行的上下文,在本例中是按钮。将自定义数据存储在以 data 为前缀的属性中 - 以确保它们不受干扰 - 标准做法。