我显示的按钮与查询中的行数一样多。每一行都有自己的名字& &;属性。当我单击任何按钮时,它应该将特定的值传递给函数。但是,当我尝试使用下面的代码时,如果我单击任何按钮,它只传递第一个值。
<?php
while ($rec = mysql_fetch_array($query)) {
echo "<figure>";
echo "<button onclick='change()' title='".$rec["UserName"]."' class='fa fa-user' id='myButton1' value='".$rec["UserName"]."' style='font-size:100px;color:red'></button>";
echo "<figcaption>".$rec["UserName"]."</figcaption>";
echo "</figure>";
//echo "</a>";
}
?>
<script type="text/javascript">
function change()
{
var elem = document.getElementById("myButton1");
alert(elem.value);
// SQL Query and display the results in a proper table <?php echo "<table><tr><td>".elem.value."</td></tr></table>"; ?>
}
</script>
如何使它传递动态值(点击任何按钮,它应该传递相应的值)?
id
值在HTML中必须唯一。具有相同id
的多个元素是无效的,并且不会按预期工作。
你根本不需要id
。相反,最小的变化是将this
传递到函数中:
<button onclick='change(this)' ... >
和你的函数
function change(btn) {
alert(btn.value);
}
但真正的答案是不要使用onclick
属性事件处理程序。它们是20世纪90年代中期的技术。20年来,一切都发生了变化。
在本例中,我将在所有这些图形所在的容器上使用委托处理程序。你可以使用更靠近它们的容器,但在最坏的情况下,你可以使用document.body
:
在按钮上放置一个共同的标识特征(例如,class
),然后:
$(document.body).on("click", ".the-class", function() {
alert(this.value);
});
一个处理程序处理所有按钮,因为click
气泡。
同样,您可能希望容器更靠近图形列表,而不是document.body
。
<?php
while ($rec = mysql_fetch_array($query)) {
echo "<figure>";
echo "<button onclick='change(this.value)' title='".$rec["UserName"]."' class='fa fa-user' id='myButton1' value='".$rec["UserName"]."' style='font-size:100px;color:red'></button>";
echo "<figcaption>".$rec["UserName"]."</figcaption>";
echo "</figure>";
//echo "</a>";
}
?>
<script type="text/javascript">
function change(button_val)
{
alert(button_val);
// SQL Query and display the results in a proper table <?php echo "<table><tr><td>".button_val."</td></tr></table>"; ?>
}
</script>