gpt4 book ai didi

javascript - 从多个按钮获取值(value)

转载 作者:行者123 更新时间:2023-12-03 07:30:30 25 4
gpt4 key购买 nike

我正在尝试从多个按钮打印一个值。按钮的值和 ID 在我的表中定义。这对于表中只有一个元素有效,但对于多个元素则不行。我想我需要以某种方式循环它。有什么建议么?(PS。不一定是按钮)

<?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>

关于javascript - 从多个按钮获取值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35823144/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com