0

.load()我有一个用于动态添加标题的 html 网页。我还使用 firebase Auth 进行身份验证,用于.onAuthStateChanged()识别用户是否登录。主 html 文档和动态添加的 html 中都有元素,其中的函数.onAuthStateChange()需要与之交互。

所以,我试图在.onAuthStateChange函数中创建自定义触发器。当我尝试向它添加选择器时,$(document).on('trigger','selector', function (){...});它似乎不起作用。如果我不使用选择器(即$(document).on('trigger', function (){...});),那么它可以工作......所以问题似乎出在选择器上。我不确定为什么选择器不起作用。或者如果触发器真的是做到这一点的最佳方式。任何和所有的帮助将不胜感激!

这是代码的缩写版本:

主要HTML:

<body>
  <header></header>
  <div class="calssName></div>

  <script>

      $(function(){
        $("header").load("header.html");
      });

      $(document).on('sgnIn','.calssName',function(){
         console.log("signed in");
         $(this).doSomeStuff;
      });

      $(document).on('sgnOut','.calssName',function(){
         console.log("signed in");
         $(this).doSomeStuff;
      });

     firebase.auth().onAuthStateChanged(firebaseUser => {
       if(firebaseUser) {  
         $(document).trigger('sgnIn');
       }
       else{
         $(document).trigger('sgnOut');
       }
    });
  </script>
</body>

标题 HTML:

<div class="calssName>
</div>

回答:我感谢所有帮助,但最终最好的解决方案是迁移到专门为此功能构建的框架(React 或 Angular)。我无法让它与原始 html 和 javascript 一起工作。

4

2 回答 2

0

$(document)只是delegateTarget,但该事件将绑定到当前或未来的'.calssName'元素,因此您可能想要这样做$('.calssName').trigger('sgnIn');(而不是$(document).trigger('sgnIn');

于 2019-12-14T17:41:40.090 回答
0

您必须在附加事件的元素上触发事件,而不是$(document).

    <script>
        //...
        firebase.auth().onAuthStateChanged(firebaseUser => {
          if(firebaseUser) {
            $('.className').trigger('sgnIn');
          } else {
            $('.className').trigger('sgnOut');
          }
        });
    </script>
于 2019-12-14T17:43:08.437 回答