开发者

passing php variable in onClick function

开发者 https://www.devze.com 2023-03-18 00:23 出处:网络
I want to pass the php variable value in onClick function. When i pass the php variable, in the UI i am getting the variable itself instead I need the value in the variable.

I want to pass the php variable value in onClick function. When i pass the php variable, in the UI i am getting the variable itself instead I need the value in the variable.

Below is code snippet, please help me.

<?php
print '<td开发者_高级运维>'; 
$node  = $name->item(0)->nodeValue;
$insert= "cubicle"."$node<br>";
Echo '<a href= "#" onClick= showDetails("$node");>'. $insert .'</a> ';
print '</td>';
?>


Variable parsing is only done in double quoted strings. You can use string concatenation or, what I find more readable, printf [docs]:

printf('<a href= "#" onClick="showDetails(\'%s\');">%s</a> ', $node, $insert);

The best way would be to not echo HTML at all, but to embed PHP in HTML:

<?php
    $node  = $name->item(0)->nodeValue;
    $insert = "cubicle" . $node;
?>

<td> 
    <a href= "#" onClick="showDetails('<?php echo $node;?>');">
        <?php echo $insert; ?> <br />
    </a>
</td>

You have to think less about quotes and debugging your HTML is easier too.

Note: If $node is representing a number, you don't need quotations marks around the argument.


you shouldn't be wrapping $node in '"':

Echo '<a href= "#" onClick= showDetails($node);>'. $insert .'</a> ';

If you want the value of $node to be in a string, thn i would do:

Echo '<a href= "#" onClick= showDetails("' . $node. '");>'. $insert .'</a> ';


$var = "Hello World!";
echo "$var"; // echoes Hello World!
echo '$var'; // echoes $var

Don't mix up " and ', they both have importance. If you use some " in your string and don't want to use the same character as delimiter, use this trick:

echo 'I say "Hello" to ' . $name . '!';


I think you are searching for PHP function json_encode which converts PHP variable into JavaScript object.

It's more secure than passing the value right in the output.


Echo '<a href= "#" onClick= showDetails("'.$node.'");>'. $insert .'</a> ';


I have been using curly braces lately instead of concatenation. I think it looks better/is more readable, and mostly I find it is easier and less prone to human error - keeping all those quotes straight! You will also need quotes around the contents inside of onClick.

Instead of this:

Echo '<a href= "#" onClick= showDetails($node);>'. $insert .'</a> ';

Try this:

Echo '<a href= "#" onClick= "showDetails({$node});">{$insert}</a> ';

As a side note, I usually use double quotes to wrap my echo statement and strictly use single quotes within it. That is just my style though. However you do it, be sure to keep it straight. So my version would look like this:

echo "<a href='#' onClick='showDetails({$node});'>{$insert}</a>";
0

精彩评论

暂无评论...
验证码 换一张
取 消