如何在按下按钮时修改Meteor模板
How to modify a Meteor template when pressing a button?
所以我正在创建一个简单的民意调查应用程序。我有一个有3个字段的表格,其中3个字段是投票问题的答案。我想做的是创建一个按钮,这样我就可以在需要时动态创建更多的字段。
但我对如何进行感到困惑
<template name="pollForm">
<form class="new-poll">
<div class="form-group">
<label>Question</label>
<input type="text" name="question" placeholder="Your Question">
</div>
<div class="form-group">
<label>Choice #1</label>
<input type="text" name="choice1" placeholder="Choice #1">
</div>
<div class="form-group">
<label>Choice #2</label>
<input type="text" name="choice2" placeholder="Choice #2">
</div>
<div class="form-group">
<label>Choice #3</label>
<input type="text" name="choice3" placeholder="Choice #3">
</div>
</form>
</template>
如何修改模板的HTML以便添加更多字段?
您可以注册一个点击事件,并使用JavaScript或jQuery:添加新的HTML元素
$('<div>').attr('class', 'form-group').insertBefore('#add-choice');
$('<label>').text('Choice #1').appendTo('form div.form-group:last');
$('<input>').attr('type', 'text').attr('name', 'choice1').attr('placeholder', 'Choice 1').appendTo('form div.form-group:last');
另一种方法是使用本地(客户端)Meteor集合,并在单击按钮时插入文档:
Choices = new Mongo.Collection(null);
if (Meteor.isClient) {
Template.pollForm.events({
'click #add-choice': function () {
Choices.insert({'label': 'Choice #123', 'placeholder': 'Choice #123', 'name': "choice123"});
}
});
Template.pollForm.helpers({
choices: () => Choices.find()
});
Template.pollForm.onRendered(function () {
Choices.insert({'label': 'Choice #1', 'placeholder': 'Choice #1', 'name': "choice1"});
Choices.insert({'label': 'Choice #2', 'placeholder': 'Choice #2', 'name': "choice2"});
Choices.insert({'label': 'Choice #3', 'placeholder': 'Choice #3', 'name': "choice3"});
});
}
<template name="pollForm">
<form class="new-poll">
<div class="form-group">
<label>Question</label>
<input type="text" name="question" placeholder="Your Question">
</div>
{{#each choices}}
<div class="form-group">
<label>{{label}}</label>
<input type="text" name="{{name}}" placeholder="{{placeholder}}">
</div>
{{/each}}
<button type="button" id="add-choice">Add choice</button>
</form>
</template>
相关文章:
- 在Safari执行javascript之前对其进行修改
- Meteor如何接收HTTP请求
- Meteor-将选定窗体中的对象添加到集合中
- Meteor上的启动页面
- Meteor方法在客户端返回null,在客户端运行的相同方法返回正确的值
- Meteor-添加用户自定义字段的方法不起作用
- 从客户端获取修改后的对象,并将其与服务器上的原始对象组合
- Meteor忘记了密码的实现
- 链接所有<a>Meteor
- 在Meteor项目中安装并包含npm模块后出错
- Meteor JS中代码的重复使用部分
- Meteor Router数据函数被调用两次
- 用Javascript修改内部标记的CSS规则
- 基于localStorage的Meteor激活模板
- React+Meteor:this.ops返回未定义
- Meteor:在模板接受Mongo查询结果之前修改它的最佳实践
- 如何修改CSS或JS文件从“;具体化:具体化;Meteor包装
- 如何在按下按钮时修改Meteor模板
- 修改Meteor-React待办事项列表示例,显示一个时间范围内创建的列表项
- 如何在 Meteor 本地对包进行轻微修改