【发布时间】: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