Meteor - 在模板加载时将类添加到 DOM 元素

Meteor - add class to DOM element on template load

本文关键字:添加 DOM 元素 加载 Meteor      更新时间:2023-09-26

>我正在尝试将一个类添加到作为我所有 DOM 树的父级的 DOM 元素中。我尝试了不同的方法:

//this one doesn't work at all. DOM is not loaded
Template.home.created = function() {
    Meteor.startup(function() {
        $("#wrapper").addClass('app');
   });
}
//this one only works if you do a page load, not if you render the template through a link (using router)
Template.home.created = function() {
    Meteor.startup(function() {
        $(document).ready(function() {
            $("#wrapper").addClass('app');
        });
   });
}
//also does not work if I click on a link
Template.home.created = function() {
    $(document).ready(function() {
        $("#wrapper").addClass('app');
   });
}
//does not work at all (I really expected this one to work by clicking on a link (using router))
Template.home.created = function() {
    $("#wrapper").addClass('app');
   });
}

我想要做的再简单不过了:添加一个类,以便我可以根据每个模板设置包装器的样式。有关如何执行此操作的任何建议将不胜感激。

当模板的实例初始化但不等待 DOM 准备好进行操作时,将调用模板创建的方法。

使用模板渲染方法,该方法将在模板呈现 DOM 时调用(第一次加载一次,每次模板中的标记更改时)

这样的东西应该可以工作(尚未测试):

Template.home.rendered = function(){
    var element = $("#wrapper");
    if(!element.hasClass("app")){
        element.addClass("app"); 
    }
}

尝试使用 Template.home.rendered 而不是 Template.home.created 。 不要在其中使用Meteor.startup$(document).ready

http://docs.meteor.com/#template_rendered

创建模板对象时调用Template.home.created,但此时尚未将任何内容呈现到 dom 节点中。