我的代码中出现此错误..
echo "<input type='button' value='send mails' onclick=\"sendmails(".$sendQuestion.")\">";
发表这个问题我有点觉得很愚蠢。但我无法弄清楚这段代码中的错误
此代码是用php编写的。如果我没有在sendmails函数中传递任何参数,它工作正常,但是当我传递参数时,它会给出错误:
missing ) after argument list
sendmails(Type your Question here testin to post from chrome)
答案 0 :(得分:2)
在其周围添加引用:
echo "<input type='button' value='send mails' onclick=\"sendmails('".$sendQuestion."')\">";
如果没有引号,javascript会误读你的字符串。
答案 1 :(得分:2)
如果您查看生成的HTML,它看起来像这样:
<input type='button' value='send mails' onclick="sendmails(Type your Question here testin to post from chrome)">
作为参数传递给JS函数sendmails
所以,我会说在它周围添加一些引用;有点像这样:
echo "<input type='button' value='send mails' onclick=\"sendmails('".$sendQuestion."')\">";
编辑:添加更多内容......
但是,如果$sendQuestion
包含引号,它会给你带来另一个错误......所以它可能对你有用
'
与\'
替换为str_replace
json_encode
第二个解决方案将为您提供类似这样的PHP代码(请注意json_encode
在字符串周围添加双引号...因此在函数调用中直接嵌入变得更加困难...所以让我们使用一个变量:
$sendQuestion = "Type your Question' here testin to post from chrome";
$json = json_encode($sendQuestion);
echo '<script type="text/javascript">' . "\n";
echo 'var myString = ' . $json . ';' . "\n";
echo '</script>' . "\n";
echo "<input type='button' value='send mails' onclick=\"sendmails(myString)\">";
生成的HTML将是:
<script type="text/javascript">
var myString = "Type your Question' here testin to post from chrome";
</script>
<input type='button' value='send mails' onclick="sendmails(myString)">
哪个更好:-)
也许还不完美......但是,到现在为止,我认为你明白了这一点; - )
作为旁注:json_encode
仅在PHP 5.2之后才存在...所以你可能想检查你正在使用的PHP版本......
答案 2 :(得分:1)
你做错的第一件事是在JavaScript引擎报告错误时发布一些PHP代码。
要调试它,JavaScript很重要。我们可以猜出JS可能会是什么样子,但是如果我们能够看到JS开始的话会更容易。
在这种情况下,最可能的解释是你想编写一些其中包含字符串文字的JS - 但你不是用引号标记JS参数。
答案 3 :(得分:0)
将PHP视为模板引擎。试试这个:
?>
<input
type="button"
value="Send mails"
onClick="sendmails('<?php echo $sendQuestion; ?>');">
<?php