【发布时间】:2015-12-17 03:53:06
【问题描述】:
我想以响应方式设置 HTML <select> 元素的值,而不更改元素的各种选项。我找到了一个解决方案,但它并不优雅。
要进行测试,请使用create meteor select 创建一个准系统 Meteor 应用,并将 select.html 和 select.js 文件的内容更改为以下内容:
选择.html
<body>
{{> select}}
</body>
<template name="select">
<label for="select">{{category}}</label>
<select id="select">
<option value='' disabled selected style='display:none;'>Select...</option>
<option value="Animal">Animal</option>
<option value="Vegetable">Vegetable</option>
<option value="Mineral">Mineral</option>
</select>
</template>
select.js
if (Meteor.isClient) {
Session.set("category", "")
Session.set("label", "Category")
Template.select.onRendered(function () {
setSelectValue()
})
Template.select.helpers({
category: function () {
setSelectValue()
return Session.get("label")
}
});
function setSelectValue() {
var select = $("#select")[0]
if (select) {
select.value = Session.get("category")
}
}
}
现在启动您的应用。在浏览器控制台中,您可以更改category Session 变量的值:
Session.set("category", "Animal")
但是,在您更改标签之前,选择元素不会更新:
Session.set("label", "category") // was "Category'
现在选择元素更新,任何后续更改category Session 变量也将更新选择元素。
Session.set("category", "Vegetable") // Now the select element updates
不使用这种笨拙的解决方法,是否可以直接达到相同的效果?
【问题讨论】:
标签: meteor html-select reactive-programming