使用Meteor反复设置选择HTML元素的值

Jam*_*ton 6 html-select reactive-programming meteor

我想<select>反应性地设置HTML 元素的值,而不更改元素的各种选项.我找到了一个解决方案,但它并不优雅.

要测试,请创建一个准系统Meteor应用程序,create meteor select并将select.html和select.js文件的内容更改为以下内容:

select.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>
Run Code Online (Sandbox Code Playgroud)

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")
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

现在启动您的应用.在浏览器控制台中,您可以更改categorySession变量的值:

Session.set("category", "Animal")
Run Code Online (Sandbox Code Playgroud)

但是,在更改标签之前,select元素不会更新:

Session.set("label", "category") // was "Category'
Run Code Online (Sandbox Code Playgroud)

现在select元素更新,任何后续更改categorySession变量也将更新select元素.

Session.set("category", "Vegetable") // Now the select element updates
Run Code Online (Sandbox Code Playgroud)

是否有可能直接实现相同的效果,而不使用这种笨拙的解决方法?

Eli*_*ock 8

是.你可以这样做:

  <select id="select">
    <option value="Animal" {{animalSelected}}>Animal</option> 
    <option value="Vegetable" {{vegetableSelected}}>Vegetable</option>
    <option value="Mineral" {{mineralSelected}}>Mineral</option>
  </select>
Run Code Online (Sandbox Code Playgroud)

看起来像这样的助手:

  Template.select.helpers({
    animalSelected: function () {
      return (someCondition === true) ? 'selected' : '';
    },
    vegetableSelected: function () {
      return (someOtherCondition) ? 'selected' : '';
    }
  });
Run Code Online (Sandbox Code Playgroud)

更好的方法可能是这样的:

  <select id="select">
    {{#each options}}
      <option value="{{value}}" {{selected}}>{{label}}</option> 
    {{/each}}
  </select>
Run Code Online (Sandbox Code Playgroud)

然后你可以this在助手中使用来决定选择什么和不选择什么.

另一种选择是使用标准jQuery来更改选择框.像这样的东西:

$('[name=options]').val( 3 );
Run Code Online (Sandbox Code Playgroud)

或者这个SO答案.