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

Get selected option text in ractive.js

我使用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>

一种方法是使用国家/地区对象本身进行绑定:

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 );
});
<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>

另一种方法是使用类似 lodashfindWhere 方法来查找相关项目:

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

显然,这样需要输入更多的代码,而且效率较低(因为您每次都需要进行查找),所以我建议您采用第一种方式。

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

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>