我试图从几个按钮打印一个值。按钮的值和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>
答案 0 :(得分:1)
尝试以下方法:
<?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>