在php和javascript onClick之间传递带有空格的值

Passing values with space between from php to javascript onClick

本文关键字:空格 php javascript onClick 之间      更新时间:2023-09-26

我找不到答案,花了很长时间这就是我的问题:我想把php变量传递给javascript onclick,但如果变量的值之间有空格,我就失败了。例如,在一个变量中传递名字和姓氏是无效的,但传递一个用户名是有效的。

这是代码:

       //$username='Liberty Johnson';//This one is not working
       $username='LibertyJohnson';
     <tr>
     <td><b>
     <?php echo $username?>
     </b> is online now <a href="javascript:void(0)" 
      onclick=  "javascript:chatWith('<?php echo    $username?>')"> 
      Start Chat</a>
      </td>
      </tr>

    function chatWith(chatuser) {
        createChatBox(chatuser);
        $("#chatbox_" + chatuser + " .chatboxtextarea").focus();
    }

需要将white space更改为&nbsp;。所以你可以使用

<?php echo str_replace(' ', '&nbsp;', $username); ?>

而不是

<?php echo $username; ?>

试试这个

function chatWith(chatuser) {
    createChatBox(chatuser);
    $("[id='chatbox_" + chatuser + "'] .chatboxtextarea").focus();
}