简体   繁体   中英

Using JS function with parameters in php

The JS function is

function func(arg){  
    alert(arg);  
}

When I do

echo "<div onclick=\"func($arg)\">Text</div>";

in php, it doesnt work but when I do

echo "<div onclick=\"func()\">Text</div>";

it works and an alert with undefined text pops up.

How do I pass argument?

You need to quote the arguments. eg

<?php
$foo = 'bar';
?>

echo "function($foo) { ... }";

is going to produce the code

function(bar) { ... }

where bar will be interpreted as an undefined variable.

Safest method is to output your PHP variables via json_encode(), to guarantee you're producing syntactically valid javascript. eg

echo 'function(' . json_encode($foo) . ') { ... }';

which would produce (in this case)

function ('bar') { ... }

You need to wrap $arg in quotes. Example:

echo "<div onclick=\\"func('$arg')\\">Text</div>";

(using single quotes around arg as you're using double quotes for the string)

您可以这样做(如果$ args当然存在)

echo '<div onclick="func('.$arg.')">Text</div>';

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