【问题标题】:Get contents of Meteor template获取 Meteor 模板的内容
【发布时间】:2015-05-27 05:04:14
【问题描述】:

我有以下 Meteor 模板:

<template name="homeBoxTpl">
    <div>
        Some content
    </div>
</template>

我有一个事件绑定,因此当单击页面上的按钮时,它应该获取模板“homeBoxTpl”的 html 内容 - 如何实现?

【问题讨论】:

    标签: templates meteor


    【解决方案1】:

    澄清一下,按钮在哪里?它在另一个模板中吗?我假设你只渲染一次homeBoxTpl。

    在这种情况下,您的按钮所在模板的事件处理程序将不会引用另一个模板实例。 没有全局查找,您可以在其中找到特定 Template 的所有渲染实例

    您必须为其设置一个唯一标识符“id”,或其他一些识别信息,例如类/属性,并通过老式 JS DOM 选择器/遍历找到它。

    document.getElementById 最快,但如果该模板有多个实例,t.firstNode 确实为您提供了一个很好的 DOM 遍历起点。

    但是,让您的代码依赖于特定的 DOM 布局是不好的做法/过多的耦合。是否有任何理由说明模板的 HTML 内容底层的数据在会话或集合等其他地方不可用?访问数据而不是 HTML 可能会更灵活。

    【讨论】:

      【解决方案2】:

      你需要的是一个event handler,就像Chase说你可以使用jquery访问meteor模板的内容,但是meteor有它自己的方式。为了获得 html 的副本,您可以在模板中的内容周围放置一个包装器,然后执行以下操作:

      Template.homeBoxTpl.events({
        'click #someButton':function(e,t){
             var templateContents = t.$('.wrapperInTemplate').html();  
        }
      })
      

      这里我们使用Template.$,它返回一个相同元素的jQuery对象。

      查看Template.instances 了解更多信息

      【讨论】:

        【解决方案3】:

        您可以使用 jquery 来访问您需要的内容。例如,如果您有以下模板:

        <template name="homeBoxTpl">
            <div class="content-container">
                Some content
            </div>
            <button id="btn" type="button">Click me</button>
        </template>
        

        然后使用以下javascript:

        Template.homeBoxTpl.events({
            'click #btn': function(e) {
                e.preventDefault();
                var content = $(".content-container").text();
                console.log(content); //Result is "Some content"
            }
        });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-11-17
          • 1970-01-01
          • 2014-12-12
          • 2017-09-16
          • 2016-04-02
          • 2016-02-21
          相关资源
          最近更新 更多