【问题标题】:How do I get button's ID from a list of buttons?如何从按钮列表中获取按钮的 ID?
【发布时间】:2015-05-10 04:23:16
【问题描述】:

我对 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 查询。这样的事情通常是怎么做的,请帮忙。

【问题讨论】:

标签: javascript php html mysql button


【解决方案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 中,标记“this”指的是代码运行的上下文,在这种情况下是按钮。将自定义数据存储在以 data- 为前缀的属性中,以确保它们不受干扰 - 标准做法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-16
    • 1970-01-01
    • 2018-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多