.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 一起工作。