如何在 php 中插入 javascript?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5025326/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I insert javascript in php?
提问by snooker841
I'm trying to insert javascript into a div. All of this is within a php document.
我正在尝试将 javascript 插入到 div 中。所有这些都在一个 php 文档中。
I am trying to get a div to fade into view when it's child div is loaded. Parent div had id of 'subemail' (this is hidden) Child div with id 'error' is shown then it should fade in the above div.
我试图让一个 div 在它的子 div 加载时淡入视图。父 div 的 id 为“subemail”(这是隐藏的) 显示 id 为“error”的子 div 然后它应该在上面的 div 中淡出。
Following is the script I'm trying to load but get error unexpected T_STRING, expecting ',' or ';'.
以下是我正在尝试加载但出现意外 T_STRING 错误的脚本,需要 ',' 或 ';'。
<script type="text/javascript">
$(function(){$('div#subemail').fadeIn('slow');});
</script>
The PHP document:
PHP文档:
if (empty($_POST['sub_name'])) {
$errors[] = 'Please type in your name';
} else {
$sub_name = strip_tags($_POST['sub_name']);
}
if (filter_input(INPUT_POST, 'sub_email', FILTER_VALIDATE_EMAIL)) {
$sub_email = $_POST['sub_email'];
} else {
$errors[] = 'Please type in a valid email';
}
if ($errors) {
echo '<div class="errors">';
echo '<script type="text/javascript">';
echo '$(function(){$('div#subemail').fadeIn('slow');});';
echo '</script>';
foreach ($errors as $error) {
echo '<p class="error">- ' . $error . '</p>';
}
echo '</div>';
}
回答by meagar
You need to escape your quotes with backslashes:
你需要用反斜杠来转义你的引号:
echo '$(function(){$(\'div#subemail\').fadeIn(\'slow\');});';
The problem is you're opening a string with the first ', and closing it at 'div#.... rather than closing it at the end of the line. Most languages use a backslash to denote a quote which is part of the string, rather than terminating the string.
问题是你用第一个打开一个字符串',然后在'div#.... 而不是在行尾关闭它。大多数语言使用反斜杠来表示作为字符串一部分的引号,而不是终止字符串。
You could also switch contexts, which I think cleans things up drastically; just be sure to separate your view/controller logic by moving the below to a template file of some kind:
你也可以切换上下文,我认为这可以彻底清理;请务必通过将以下内容移动到某种模板文件来分离您的视图/控制器逻辑:
<? if ($errors) { ?>
<div class="errors">
<script type="text/javascript">
$(function() { $('div#subemail').fadeIn('slow'); });
</script>
<? foreach ($errors as $error) { ?>
<p class="error"><?= $error ?></p>
<? } ?>
</div>
<? } ?>
回答by rickypai
alternatively, you can write
或者,你可以写
echo "$(function(){$('div#subemail').fadeIn('slow');});";
回答by yoda
echo "$(function(){$('div#subemail').fadeIn('slow');});";

