在ractive.js中获取所选选项文本

Get selected option text in ractive.js

本文关键字:选项 文本 获取 ractive js      更新时间:2023-09-26

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

<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: ['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>

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

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>

另一种选择是使用类似lodash的findWhere方法找到相关项目:

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

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