javascript - 当我运行 return () 时? "": "" syntax in Javascript, 仅当我将文件另存为 PHP 而不是 HTML 时,我才在 Google Chrome 中收到错误

标签 javascript php html

我是一般编程新手,偶然发现了一个我无法自行解决的错误。我创建了一个包含 <script> 的 HTML 文件标签,然后是一个运行 return () ? "" : "" 的函数语法和一切都在我的浏览器中正常工作。但是,当我将完全相同的代码放入 PHP 标记中时,我在 Google Chrome 中收到上述错误,提示““Uncaught SyntaxError: Unexpected token return””并指定带有 return () ? "" : "" 的行。句法。完全相同的代码被保存到 PHP 文件,但被 <?php ?> tags 包围. HTML 文件中的代码是:

<!DOCTYPE html>
<html>
  <head>
    <title>An Example </title>
    <script>
      function validateForename(field)
      {
        return (field == "") ? "No Forename was entered.\n" : ""
      }

    </script>
  </head>

</html>

PHP 文件中的代码是:

<?php
echo <<<_END
<!DOCTYPE html>
<html>
  <head>
    <title>An Example </title>
    <script>
      function validateForename(field)
      {
        return (field == "") ? "No Forename was entered.\n" : ""
      }

    </script>
  </head>

</html>

_END
?>

有什么想法吗?

最佳答案

Variables in PHP are represented by a dollar sign followed by the name of the variable

参数必须作为 $var_name 传递。您在这里缺少 $。另请注意,您必须以 ;

结束语句

试试这个:

<?php
function sample($name){return ($name == "") ? "None./n" : "";}
    echo 'Hello ', 'World!' , '<br />'.sample('');      
?>

当您使用 php 回显 整个字符串时,它会将 \n 视为新行。使用 \\ 转义该字符。例如:(return (field == "") ? "No Forename was entered.\\n": "")

关于javascript - 当我运行 return () 时? "": "" syntax in Javascript, 仅当我将文件另存为 PHP 而不是 HTML 时,我才在 Google Chrome 中收到错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34735576/

相关文章:

javascript - 如何从 Node js服务器向客户端显示shell脚本的结果?

javascript - 如何根据字符串在每个元素中的位置对 PHP 数组进行排序?

php - 如何访问javascript对象数组中的条目

phpcurl,链接标签提取

html - 表格行和单元格损坏

javascript - 仅使用 javascript 旋转产品图像

javascript - 有没有一种方法可以从多个 SQL 表中提取一个 DataTables 表?

javascript - 从 jquery 插件中获取 iframe 的文档变量?

asp.net - <div> 标签中的标签控件左对齐

jquery onclick 不起作用