简体   繁体   English

在php变量上调用javascript函数

[英]Calling a javascript function on a php variable

Javascript: Javascript:

function capitalizeFL(string) { 
    return string.charAt(0).toUpperCase() + string.slice(1);
}

PHP: PHP:

echo "You have chosen a <script>document.write(capitalizeFL(".$race."));</script>";

$race contains a string. $race包含一个字符串。 What I would like is simply to capitalize the first letter of the php variable $race , using the Javascript function above, and print it on the page. 我想要的只是使用上面的Javascript函数将php变量$race的首字母大写,并将其打印在页面上。

I could find another way of doing this, but this JS-PHP mixing thing is confusing to me and I'd very much like to figure out WHY this doesn't work. 我可以找到另一种方式,但是这种JS-PHP混合的方式令我感到困惑,我非常想弄清楚为什么这行不通。

Look at the generated JavaScript. 查看生成的JavaScript。

document.write(capitalizeFL(value_of_race));

That's an identifier, not a string literal. 那是一个标识符,而不是字符串文字。 You need to include quote marks in your generated JS. 您需要在生成的JS中添加引号。

Given a string, the json_encode function will output the equivalent JS literal (even if it isn't valid JSON). 给定一个字符串, json_encode函数将输出等效的JS文字(即使它不是有效的JSON)。 Use that to convert your PHP variables into JS literals. 使用它可以将您的PHP变量转换为JS文字。

$js_race = json_encode($race);
echo "You have chosen a <script>document.write(capitalizeFL($js_race));</script>";
echo "You have chosen a <script>document.write(capitalizeFL('".$race."'));</script>";

You can try above code. 您可以尝试上面的代码。 Javascript string must be wrapped by ''. JavaScript字符串必须用”换行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM