在ractive.js中获取选定的选项文本

时间:2015-03-26 17:54:14

标签: javascript ractivejs

我使用ractive.js绑定一个选择框。我应该将选项的id提交给服务器,所以我使用id和name。但是为了显示,我应该显示选项的文本。

<select value='{{selectedCountry}}'>
    {{#countries}}
        <option value='{{id}}'>{{name}}</option>
    {{/countries}}
</select>

ractive = new Ractive({
    el: myContainer,
    template: myTemplate,
    data: {
        countries: [
            { id: 1, name: 'Afghanistan' },
            { id: 2, name: 'Albania' },
            { id: 3, name: 'Algeria' }
        ]
    }
});

但我只能获取id,如何获取选项中的文本?

<div>
{{selectedCountry}}
</div>

2 个答案:

答案 0 :(得分:4)

以下是如何使用简单数组:

ractive = new Ractive({
  el: 'main',
  template: '#template',
  data: {
    countries: ['Afghanistan','Albania','Algeria']
  }
});

ractive.observe( 'selectedCountryId', function ( id ) {
  console.log( 'saving %s to server', id );
});
<script src='http://cdn.ractivejs.org/latest/ractive.js'></script>

<script id='template' type='text/html'>
  <select value='{{selectedCountryId}}'>
    {{#countries:i}} <!-- add a semicolon and an identifier to use index during iteration -->
      <option value='{{i+1}}'>{{this}}</option>
    {{/countries}}
  </select>
  
  <p>selected country: {{selectedCountryId}}/{{countries[selectedCountryId-1]}}
  </p>
</script>

<main></main>

答案 1 :(得分:3)

一种方法是使用country对象本身进行绑定:

&#13;
&#13;
ractive = new Ractive({
  el: 'main',
  template: '#template',
  data: {
    countries: [
      { id: 1, name: 'Afghanistan' },
      { id: 2, name: 'Albania' },
      { id: 3, name: 'Algeria' }
    ]
  }
});

ractive.observe( 'selectedCountry', function ( country ) {
  console.log( 'saving %s to server', country.id );
});
&#13;
<script src='http://cdn.ractivejs.org/latest/ractive.js'></script>

<script id='template' type='text/html'>
  <select value='{{selectedCountry}}'>
    {{#countries}}
      <option value='{{this}}'>{{name}}</option>
    {{/countries}}
  </select>
  
  <p>selected country:
    {{selectedCountry.id}}/{{selectedCountry.name}}
  </p>
</script>

<main></main>
&#13;
&#13;
&#13;

替代方法是使用lodash findWhere方法找到相关项:

ractive.observe( 'selectedCountry', function ( id ) {
  var country = _.findWhere( this.get( 'countries' ),  { id: id });
  this.set( 'selectedCountryName', country.name );
});

显然,键入的代码更多,效率更低(因为每次都需要进行查找),所以我建议第一种方法。