简体   繁体   中英

Pass ID on onClick Function in Javascript

I am trying to pass the email using the onClick function and I want to show that email in alert:

<td>
   <button class="btn btn-primary" name="buton" onclick="myfunction(<?php  $email;   ?>)" >Edit</button>
</td>

Here is my function:

<script type="text/javascript">
    function myfunction(id)
    {
        alert(id);
    }
</script>

 function myfunction(id) { alert(id); } 
 <td> <button class="btn btn-primary" name="buton" onClick="myfunction('<?php echo $email; ?>')" >Edit</button></td> 

You need to put the email in 'single quotes'

当您传递电子邮件(字符串)时,请尝试此操作,它应该在quote ,而在JavaScript中使用php时,在这种情况下,您必须使用echo

<td><button class="btn btn-primary" name="buton" onclick="myfunction('<?php  echo $email;   ?>')" >Edit</button></td>

What you want is probably the PHP tag <?= that echoes the $email variable as an argument to the JavaScript function. Note that you will need quotation marks for the email:

onclick='myfunction("<?= $email ?>")'

If shorttags are not enabled the long version must be used:

onclick='myfunction("<?php echo $email; ?>")'

You've to make two changes to validate your code :

  1. You should add echo to pass the php variable to JS.

  2. You need to add single quotes since the $email is a string and you've already using double quotes in onclick attribute.

     <td> <button class="btn btn-primary" name="buton" onclick="myfunction('<?php echo $email; ?>')" >Edit</button> </td> 

Your code is working, you are just not echoing the value of $email in a good way:
- Lack of the single quotes in myfunction(' … ')
- Lack of echo inside your php tags myfunction('<?php echo $email ?>')

To avoid that kind of problems…
In your php, I suggest you to use heredoc syntax:

echo <<< EOD
<td><button class="btn btn-primary" name="buton" onclick="myfunction('{$email}')">Edit</button></td>
EOD;

Note the { } around the variable. They are not necessary, but I suggest you to use them, as they make the variables more noticable.

⋅ ⋅ ⋅

The result will be:

 function myfunction(id) { alert(id); } 
 <td><button class="btn btn-primary" name="buton" onclick="myfunction('myemail@stackoverflow.com')">Edit</button></td> 

Documentation about Heredoc syntax: http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc

I hope it helps.

回显php标签中的变量

<td><button class="btn btn-primary" name="buton" onclick="myfunction('<?php  echo $email;   ?>')" >Edit</button></td>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM