背景知识:在我的应用程序中,我有这些输入文本框,当您键入它们时,它使用Session来容纳一个反应变量,以便用户可以实时查看所输入内容。

我想让用户单击按钮以添加新的输入框。每当用户在该新输入框中键入内容时,它也应该以与第一个相同的方式生成实时预览。但是,似乎事件处理程序未应用于这些新创建的元素。结果,实时预览不会更新,直到我再次在原始输入框中键入内容。

Template.makeEntry.helpers({
    goals: function() {
        return Session.get('todayGoals');
    }
});

Template.makeEntry.events({
  'input .goal': function(e) {
    var tempGoals = [];
    $('.goal').each(function(i){

        tempGoals.push($(this).val());
    });
    Session.set('todayGoals',tempGoals);
  },
  'click .add-goal': function(e) {

    var lastGoal = $('.goal').last();

    $('<input class="goal" type="text" name="goal" placeholder="Type your goal here...">').insertAfter(lastGoal);
  }
});

Template.makeEntry.rendered = function(){
    Session.set('todayGoals',[]);
}


HTML:

<template name="makeEntry">
    <h1>Sunday, February 1st</h1>
    <hr>
    <input class="goal" type="text" name="goal" placeholder="Type your goal here...">
    <button class="add-goal">Add</button>
    {{#if goals}}
        <ul>
            <li>Today's Goals
                <ul>
                    {{#each goals}}
                        <li>{{{this}}}</li>
                    {{/each}}
                </ul>
            </li>
        </ul>
    {{/if}}
</template>

最佳答案

尽量不要在Blaze之外操作DOM。

Template.makeEntry.created = function(){
  Session.set('todayGoals',[""]);
}

Template.makeEntry.events({
  'click .add-goal': function(){
    var goals = Session.get('todayGoals');
    goals.push("");
    Session.set('todayGoals', goals);
  }
});

Template.makeEntry.helpers({
  'goal': function(){
    return Session.get("todayGoals");
  }
});


并在html中

<template name="makeEntry">
  ...
  {{#each goal}}
    ... do something with goal
    <input class="goal" type="text" name="goal" placeholder="Type your goal here...">
  {{/each}}
</template>

09-25 18:00
查看更多