如何在 html 中调用 js document.ready 函数

How to call js document.ready function in html?

本文关键字:js document ready 函数 调用 html      更新时间:2023-09-26

我正在使用jquery document.ready编写一个网页游戏。当我在 html 中调用 js 函数时,它不起作用:

.js:

$(document).ready(function(){
    function init(){blablabla...}
})

.html:

<script src="function.js"></script>
<script>
function bla(){
    if (blablabla)
        init();
}
</script>

我只学习了几个星期的html和js。我不知道为什么它不起作用。

请按照下面的步骤操作:

有两个

版本的jQuery可供下载: 缩小和压缩

jQuery 库是一个单一的 JavaScript 文件,您可以使用 HTML <script> 标记引用它(请注意,<script> 标记应该在 <head> 部分中(:

喜欢:

<head>
<script src="jquery-1.12.0.min.js"></script>
</head>

您可能已经注意到,我们示例中的所有 jQuery 方法都位于文档就绪事件中:

<script>
    $(document).ready(function(){
       // jQuery methods go here...
    }); 
</script>

实现预期结果的一种方法是将init设置为document的属性

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<script>
  $(document).ready([
    function() {
      function init() {
        // do stuff
        alert("blablabla...") 
      }
      // set `init` as property of `document`
      this.init = init;
    },
    function bla() {
      if ($.isReady /* blablabla */)
        document.init();
    }
  ])
</script>
<body></body>