【问题标题】:Empty lines are breaking a Javascript script? [closed]空行正在破坏 Javascript 脚本? [关闭]
【发布时间】:2013-04-27 13:55:15
【问题描述】:

我对此感到困惑。我正在使用 WordPress 网站,我有 2 个简单的 Javascript 警报功能。我在图像的 onclick 中使用其中一个来确保脚本有效。如果我的脚本中没有任何空行,一切都很好,但是如果我添加任何空行,则没有任何效果(请参阅下面的代码以获取示例)。

Javascript 和 PHP 都忽略空格。我唯一不确定的是HTML。关于 HTML 如何处理空白的内容并不多(尽管我觉得我在某处读到,如果它不在元素中,它会忽略它)。 HTML 空格是否敏感(除了在元素中)?如果不是,为什么空行会弄乱我的脚本?我想这没什么大不了的,因为我可以删除空行,但我想让我的代码更整洁并找出导致这种情况的原因。

这是我的代码示例:

// This works fine because there's no empty lines
<script type='text/javascript'>
        function showAlert() {
            alert("The first showAlert function works!");
        }
        function showAnotherAlert("The other alert is working!");
</script>

// This won't do anything because of the empty lines between the functions
<script type='text/javascript'>
        function showAlert() {
            alert("The first showAlert function works!");
        }

        function showAnotherAlert() {
        alert("The second alert is working!");
        }
</script>

有人对此有任何见解吗?

【问题讨论】:

  • 什么是showAnotherAlert?它是在哪里定义的?
  • function showAnotherAlert("The other alert is working!"); 根本不是 javascript 中的有效语法。这两个例子都不应该工作......
  • 您忘记包含您看到的确切错误。 “不起作用”是一个糟糕的描述。换行符首先与该问题无关。我建议您也使用像 JSHint 这样的静态代码分析,它会向您指出语法错误。
  • 我们都对此感到困惑
  • 我也遇到过这个问题。如果您检查页面上的实时代码,您会注意到 wordpress 在换行符的位置添加了

    标记。不幸的是,我还没有找到解决方案,所以这就是我不回答的原因。

标签: php javascript html wordpress


【解决方案1】:

你的代码应该这样写;

<script type='text/javascript'>
    function showAlert() {
        alert("The first showAlert function works!");
    }

    function showAnotherAlert(text) {
        alert(text);
    }
</script>

使用function showAnotherAlert("The other alert is working!"); 之类的语法将不会被 Javascript 识别,因为它的格式无效。如果您希望将文本动态传递给警报,只需通过上面示例中所示的函数传递它。

【讨论】:

  • 感谢您指出这一点!我实际上只是错误地输入了代码。
猜你喜欢
  • 1970-01-01
  • 2016-07-02
  • 2013-01-17
  • 2019-02-24
  • 2022-06-16
  • 1970-01-01
  • 1970-01-01
  • 2020-10-23
  • 1970-01-01
相关资源
最近更新 更多