如何从按钮列表中获取按钮的ID?

时间:2015-03-09 03:21:40

标签: javascript php html mysql button

我没有使用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查询。通常如何做这样的事情,请帮忙。

1 个答案:

答案 0 :(得分:1)

<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中,令牌&#34;此&#34;指的是代码运行的上下文,在这种情况下是按钮。将自定义数据存储在以数据为前缀的属性中 - 以确保它们不受干扰 - 标准做法。

相关问题