从多个按钮获取价值

Getting value from multiple buttons

本文关键字:获取 按钮      更新时间:2023-09-26

我正在尝试从几个按钮打印一个值。按钮的值和 ID 在我的表中定义。这仅适用于表中的一个元素,但不适用于多个元素。我想我需要以某种方式循环它。有什么建议吗?(附言。不必是按钮)

<?php
$sql_rel = "SELECT * FROM TABLE";
$result1 = mssql_query($sql_rel);
$count = mssql_num_rows($result1);
while ($row1 = mssql_fetch_assoc($result1)){
    echo '<button id="' . $row1['NAME'] . '" onClick="func()" value="'.$row1['NAME'].'">'.$row1['DESCRIPTION'].'</button>';
}

    <p id="print"></p>
    <script>
    function func(){
       var x = document.getElementById("<?php 
       $sql_rel = "SELECT * FROM TABLE";
       $result1 = mssql_query($sql_rel);
       $count = mssql_num_rows($result1);
       while ($row1 = mssql_fetch_assoc($result1)){
          echo $row1['NAME'];
       }
     ?>").value;
   document.getElementById("print").innerHTML = x;
   }
   </script>

尝试以下操作:

<?php
$sql_rel = "SELECT * FROM TABLE";
$result1 = mssql_query($sql_rel);
$count = mssql_num_rows($result1);
while ($row1 = mssql_fetch_assoc($result1)){
    /* Note the "this" in the onClick function */
    echo '<button id="' . $row1['NAME'] . '" onClick="func(this)" value="'.$row1['NAME'].'">'.$row1['DESCRIPTION'].'</button>';
}

<p id="print"></p>
<script>
function func(obj){
    document.getElementById("print").innerHTML = obj.value;//Change to 'obj.innerHTML' for the button's visible text (aka, $row1['DESCRIPTION'])
}
</script>

第二个答案:(刷新之前不会再次更改)

<?php
$sql_rel = "SELECT * FROM TABLE";
$result1 = mssql_query($sql_rel);
$count = mssql_num_rows($result1);
while ($row1 = mssql_fetch_assoc($result1)){
    /* Note the "this" in the onClick function */
    echo '<button id="' . $row1['NAME'] . '" onClick="func(this)" value="'.$row1['NAME'].'">'.$row1['DESCRIPTION'].'</button>';
}

<p id="print"></p>
<script>
var pressed = false;
function func(obj){
    if (pressed) return;
    document.getElementById("print").innerHTML = obj.value;//Change to 'obj.innerHTML' for the button's visible text (aka, $row1['DESCRIPTION']);
    pressed = true;
}
</script>

第三个答案:(抱歉久等了)

<?php
$sql_rel = "SELECT * FROM TABLE";
$result1 = mssql_query($sql_rel);
$count = mssql_num_rows($result1);
while ($row1 = mssql_fetch_assoc($result1)){
    /* Note the "this" in the onClick function */
    echo '<button id="' . $row1['NAME'] . '" onClick="func(this)" value="'.$row1['NAME'].'">'.$row1['DESCRIPTION'].'</button>';
}

<p id="print"></p>
<script>
function func(obj){
    if (obj.pressed) return;
    document.getElementById("print").innerHTML = document.getElementById("print").innerHTML + " " + obj.value;//Change to 'obj.innerHTML' for the button's visible text (aka, $row1['DESCRIPTION']);
    obj.pressed = true;
}
</script>