【问题标题】:Set value of a select HTML element reactively with Meteor使用 Meteor 反应性地设置选择 HTML 元素的值
【发布时间】: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


    【解决方案1】:

    是的。你可以这样做:

      <select id="select">
        <option value="Animal" {{animalSelected}}>Animal</option> 
        <option value="Vegetable" {{vegetableSelected}}>Vegetable</option>
        <option value="Mineral" {{mineralSelected}}>Mineral</option>
      </select>
    

    还有看起来像这样的助手:

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

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

      <select id="select">
        {{#each options}}
          <option value="{{value}}" {{selected}}>{{label}}</option> 
        {{/each}}
      </select>
    

    然后您可以在帮助程序中使用this 来决定选择什么,不选择什么。

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

    $('[name=options]').val( 3 );
    

    this SO answer

    【讨论】:

      【解决方案2】:

      如果您希望动态设置选择,我通常使用这样的车把助手

      Template.newtask.helpers({
        filler: function(element){
          return Session.get(element);
        }
      });
      

      然后在html中

      <select class="browser-default" id="selectedService" name="jobtype">
        <option id="zero" value="{{filler 'type'}}">{{filler 'type'}}</option>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-10-22
        • 1970-01-01
        • 2011-08-06
        • 2010-11-16
        • 2014-01-10
        • 1970-01-01
        • 2019-10-13
        相关资源
        最近更新 更多