如何显示数据上的按钮点击在一个循环使用php

how to display data on button click in a loop using php

本文关键字:一个 循环 php 按钮 显示 何显示 数据      更新时间:2023-09-26

我有一个项目,我在一个while循环中显示一个按钮标签。在每次单击按钮时,我想显示一个带有相应UserId的警告框。下面是我的代码:

    <?php 
 $data = mysql_query("Select RegisterId,FName,Image1  from Information where RegisterID='$profileMonth1'") or die(mysql_error());
 while ($dis1 = mysql_fetch_array($data)) {
?>    
<div id="demo1" value="<?php echo "$RegisterId" ?>">
<button onClick="validate()">Show Interest</button>
</div> 
<?php } ?>

下面是我的validate函数:

   function validate1(id2)
                {
   // var id2;
    id2 = document.getElementById('demo2').getAttribute('value');
                alert(id2);
}

但是它总是显示我最后一个用户id…而我想在每次点击时显示每个用户的userid

有人能帮忙吗?

在这里,你调用的函数是未定义的validate1,你也不需要在你的函数声明中获得任何参数,因为当你调用它时你没有传递任何参数。

 <?php 
 $data = mysql_query("Select RegisterId,FName,Image1  from Information where RegisterID='$profileMonth1'") or die(mysql_error());
 while ($dis1 = mysql_fetch_array($data)) {
?>    
<div id="demo" value="<?php echo "$RegisterId" ?>">
<button onClick="validate()">Show Interest</button>
</div> 

JS

function validate(){
    var id2 = document.getElementById('demo').getAttribute('value');
    alert(id2);
}

在你的代码中试试

HTML:

<button onClick="validate('<?php echo $RegisterId; ?>')">Show Interest</button>
Javascript:

function validate(id2)
   {
            alert(id2);
   }

你的代码需要修改。

首先,你做了一个规定发送id到javascript函数,但是,你没有传递id给它。

PHP

<?php 
$data = mysql_query("Select RegisterId,FName,Image1  from Information where RegisterID='$profileMonth1'") or die(mysql_error());
while ($dis1 = mysql_fetch_array($data)) {
?>
<div id="demo1" value="<?php echo $dis1['RegisterId'];?>">
    <button onClick="validate('<?php echo $dis1['RegisterId'];?>')">Show Interest</button>
</div>
<?php } ?>
Javascript:

function validate1(id2) {
  // var id2;
  //id2 = document.getElementById('demo2').getAttribute('value');
  alert(id2);
}

使用此代码,您的单击甚至不应该返回最后一个id。你的javascript函数看起来不太好。

应该可以;

<?php 
$data = mysql_query("Select RegisterId,FName,Image1  from Information where RegisterID='$profileMonth1'") or die(mysql_error());
while ($dis1 = mysql_fetch_array($data)) {
?>
<!-- removed id attribute, as they're unique, you can't set it to every div. 
If you really need id attribute, you can set one by using your RegisterId (e.g. id="demo-<?php echo $RegisterId; ?>)
And moved value attribute to button tag, it's much more useful in it. -->
<div>
<button onClick="validate(this)" value="<?php echo "$RegisterId" ?>">Show Interest</button>
</div> 
<?php } ?>
Javascript

function validate(element){
    alert(element.value)
}