【发布时间】:2019-06-12 02:02:02
【问题描述】:
我似乎无法让我的 jquery <div id="NotificationDotOnNav" > {{NotificationNavDot}} </div> 函数工作!
在帮助文件下方找到:
<template name="home">
<div id="NotificationDotOnNav" > {{NotificationNavDot}} </div>
</template>
在我的帮助文件下面找到:
Template.home.helpers({
'NotificationNavDot': function () {
var numberOfNotifications = recipientsDetails.find({counts:1}).count();
if (numberOfNotifications > 0) {
$("#NotificationDotOnNav").css({ "visibility": "visible"});
alert("Testing!");
return;
}
else {
$("#NotificationDotOnNav").css({ "visibility": "hidden"});
}
},
});
运行时,会弹出Testing! 的弹出窗口,这显然意味着流实际上进入了if (numberOfNotifications > 0),但是$("#NotificationDotOnNav").css({ "visibility": "visible"}); 无法启动!
我觉得很奇怪的是,当在浏览器控制台中复制粘贴并运行:$("#NotificationDotOnNav").css({ "visibility": "visible"}); 时,它可以工作!
有人能解释一下为什么它只在浏览器控制台中运行时才会启动而不是其他情况吗?也请帮助我让这个简单的代码工作。
我已经包含了相关的 CSS 文件,以防万一这会有所帮助
#NotificationDotOnNav{
top: 10px;
float: right;
right: 5%;
visibility: hidden;
position: absolute;
z-index: 5;
min-width: 10px;
padding: 7px 7px;
border-radius: 20px;
background-color: #f54555ad;
}
期待您的帮助!
【问题讨论】:
-
这个函数的调用频率和时间是多少?创建一个工作示例来演示该问题。假设您的函数正常工作,那么问题可能是 1) 调用的函数过早 dom 尚未准备好,因此 css 行什么也不做 2) 函数多次调用,最后一次调用时,它隐藏了元素
-
在您尝试调用时,dom 元素是否已经存在?替换为 console.log($("#NotificationDotOnNav")[0]);用于测试...
-
你能把它放在codepen或其他任何地方吗?
-
@SirBT 您的函数在
#NotificationDotOnNav元素甚至在DOM 上呈现之前被调用。 -
想必元素
#NotificationDotOnNav是存在的,你的名字没有错别字吧?console.log(document.getElementById('NotificationDotOnNav'))是否记录了正确的元素?
标签: javascript jquery css meteor