【问题标题】:Javascript external function from html gives 'function not defined'来自 html 的 Javascript 外部函数给出“未定义函数”
【发布时间】:2017-03-23 20:29:56
【问题描述】:

我试图从外部加载的index.js 文件中调用 html 页面中的函数,但我总是得到

Uncaught ReferenceError: displayy is not defined

在我的 html 页面中:

 <script type="text/javascript" src="index.js"></script>

<script>
    $( document ).ready(function() {
       displayy();
    });
</script>

index.js 文件:

$( document ).ready(function() {
    alert('loaded');
      function displayy() {
    alert('executed');
    } 
 });

我也试过了:

<script>
    window.onload = function() {
        displayy();
    };
</script>

<script>

    document.addEventListener("DOMContentLoaded", function(event) {
        displayy();
    });
</script>

【问题讨论】:

  • displayy 未在您要调用的环境中定义。
  • @FelixKling 我如何在那里定义它?
  • @FelixKling 如果没有简单的方法可以做到这一点,我可以将整个 displayy 函数移动到 html 脚本标记内并从那里运行它。这样它就可以工作了。
  • 要么将函数定义移动到调用函数的位置,要么在全局范围内定义函数。 “我可以将整个 displayy 函数移动到 html 脚本标签内并从那里运行它。” 是的,那么它是在全局范围内定义的。没有理由将声明放在 document.ready 回调中。查看learn.jquery.com/using-jquery-core/document-ready 以更好地了解何时需要 document.ready。

标签: javascript jquery html


【解决方案1】:

您无需从脚本中再次运行displayy。 以下作品:

$(document).ready(function() {
      alert('loaded');
      displayy();
      function displayy() {
        alert('executed');
      } 
});
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

【讨论】:

  • 是的。我觉得自己好傻。我在所有其他文件中都这样做。不知道为什么我要全力以赴……并尝试按照我发布的方式进行操作。只是累了。谢谢你。我会接受你的答案,因为它是正确的。但是为什么它会起作用呢?在定义函数之前调用它。
  • 但是你能回答我关于你的回答的问题吗?
  • @BogdanDaniel 您甚至可以在定义之前调用该函数。不要紧。但是您需要确保在同一范围内定义它。当您从 html 调用它时,可能是它当时没有加载。但是如果你从同一个作用域调用它,你甚至可以在定义它之前调用它。
【解决方案2】:

在您的 index.js 中,您可以使用 window 对象调用您的函数。

window.displayy = function(){ 
    return "hello!" 
}

然后你调用它 window.displayy();displayy();

更好的解决方案是在更高的范围内声明您的函数,如下所示:

var displayy;

$( document ).ready(function() {
      alert('loaded');
      displayy = function () {
       alert('executed');
      } 
 });

注意:使用全局变量不好,但它应该可以解决您的问题。请看这里:I've Heard Global Variables Are Bad, What Alternative Solution Should I Use?

【讨论】:

    【解决方案3】:

    将您的函数附加到window 对象。像这样的:

    // Set the container!
    window.app = {};
    
    // Define the function.
    window.app.say_hello = function(name) {
       alert(`Hello ${name}`);
    };
    
    // Call the function.
    app.say_hello("Iran");
    

    我什么都试过了。只有这个解决方案有效。 :)

    【讨论】:

      【解决方案4】:

      删除 .js 文件中的 document.ready 包装器。

      我也遇到了这个问题。我在 document.ready 中的主 html 文件中调用了该函数,并且外部 .js 文件也将调用的函数定义包装在 document.ready 函数中。一旦我在 .js 文件中删除了该包装器,它就可以正常工作了。这允许外部 .js 文件中的函数在范围内变为全局。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-10
        • 2011-09-25
        相关资源
        最近更新 更多