javascript 警报 php 字符串 space

javascript alert php string with space

如何获取 php 值包含带有 javascript 的空格? 我下面有一个 php 代码

<?php 
    $firstName = "my first name";
    echo "<input type='button' onclick=showFirstName(".$firstName.");>";
?>

下面是我的脚本

<script>
    function showFirstName(firstName){
    alert(firstName);
}
</script>

而且那个警报不会起作用,如果像 $firstName = "My" 就不同了。 有人有解决办法吗? 谢谢 :)

只需正确添加 ' 即可。试试 -

echo "<input type='button' onclick=showFirstName('".$firstName."');>";

像这样将 onclick 函数调用放在双引号中:

$firstName = "my first name";
echo "<input type='button' onclick=\"showFirstName('$firstName');\">";

调用showFirstName方法时需要加单引号

<?php 
    $firstName = "my first name";
    echo "<input type='button' onclick=showFirstName('".$firstName."');>";
?>

试试这个,

<?php 
    $firstName = "my first name";
    echo "<input type='button' onclick='showFirstName(\"".addslashes($firstName)."\")'>"; 
?>