【问题标题】:Why is .trigger() not working when a selector is added to .on()?为什么将选择器添加到 .on() 时 .trigger() 不起作用?
【发布时间】:2019-12-14 17:20:49
【问题描述】:

我有一个使用.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 一起使用。

【问题讨论】:

    标签: jquery firebase-authentication dynamic-html jquery-trigger


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-04-30
        • 1970-01-01
        • 1970-01-01
        • 2023-03-09
        • 2017-06-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多