JQuery 触发 iife 时未捕获事件

JQuery event not caught when triggered iife

我有以下 html 文件,名为 a.html

<html>
    <head>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
        <script type="text/javascript" src="a.js"></script>
    </head>

    <body>
        <script>
            $(document).on('foo', function () {
                alert('test');
            });
        </script>
    </body>
</html>

和下面的 Javascript 文件,名为 a.js

(function() {   
    $(document).trigger('foo');
}());

当我打开a.html时,调用了a.js中的触发器调用,行

$(document).on('foo', function () {

已调用,但从未调用警报。我做错了什么?

尝试在正文末尾添加脚本文件a.js,

<body>
    <script>
        $(document).on('foo', function () {
            alert('test');
        });
    </script>
    <script type="text/javascript" src="a.js"></script>
</body>

a.js 中,您在定义之前调用触发器 foo, 尝试像这样使用 document ready 它会起作用

$(document).ready(function(){
    $(document).trigger('foo');
})

它将等待加载整个文档(以及文档中的所有脚本)

您需要像这样更新您的代码:

您可以将脚本代码放入 a.js 文件:

此处为演示:https://jsbin.com/fukujad/edit?html,output

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
   <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<script>
$(function(){
    $(document).on("test", function(){
        alert("test triggered");
    });
    $(document).trigger("test");
});
</script> 
</body>
</html>

根据我的理解,上面代码中的问题是 a.js 在下面的脚本之前加载。

<script>
    $(document).on('foo', function () {
        alert('test');
    });
</script>

并且此事件在 a.js 中被调用后将被绑定。

尝试在上面的脚本下方加载 a.js,如下所示。

<script>
    $(document).on('foo', function () {
        alert('test');
    });
</script>
<script type="text/javascript" src="a.js"></script>  

按照显示的顺序将两个脚本放在一处。

<html>
    <head>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
        <script type="text/javascript" src="a.js"></script>
    </head>

    <body>
      <label> rerwnr</label>
        <script>

        </script>
    </body>
</html>

  (function() {   
     $(document).on('food', function () { 
                  alert('test');
              });
      $(document).trigger('food');
  }());

https://codepen.io/pavankumark/pen/WExNEg

查看 link 了解更多详情。