简体   繁体   中英

Call JavaScript function(with parameters) by onclick event

I cant use PHP variables to use as parameters for my function.

The function is:

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

And this is PHP part:

echo "<button onclick='myFunction($intvar,$strvar)' type='button'>ClickMe</button>";

the call works when I use numbers like this: myFunction(0,1) but I need to use variables to call myFunction.

Please Help, thanks.

好的做法是回显json编码的变量版本,这样就可以确保字符串被正确引用:

echo "<button onclick='myFunction(" . json_encode($intvar) . "," . json_encode($strvar, JSON_HEX_APOS) . ")' type='button'>ClickMe</button>";

你试试这个function myFunction(ide,name) { change insted of id => ide echo "<button onclick='myFunction(".'"'.$intvar.'","'.$strvar.'"'.")' type='button'>ClickMe</button>";

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