在ractive.js中获取所选选项文本
Get selected option text in ractive.js
我使用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 );
});
显然,这是更多的代码类型,而且效率较低(因为每次都需要进行查找),所以我建议用第一种方式进行查找。
相关文章:
- 或者在表单上选择默认选项文本(选择1)
- 在ractive.js中获取所选选项文本
- 使用VueJs获取Select选项文本
- Rally App SDK 2.0:rallymultiobjectpicker无法加载选项文本
- 选择选项文本作为数组
- 动态更改选项文本不起作用
- 页面重定向后,使用选定的选项文本更新下拉菜单文本
- 为什么选择只显示IE 9中选项文本的第一个字符
- 如何在jquery的选择下拉列表中获取选项文本
- 如何使“所选选项”与当前“所选选项”文本的宽度相同
- 使用选择选项文本更改价格
- 使用挖空将选项文本绑定到具有对象数组的属性
- 传递要发送的数据.选择选项文本和值
- 挖空.js从 AJAX 调用获取数据后更新选项文本
- 在选择框中从任意 JavaScript 对象绑定选项值和选项文本
- 显示选择选项文本日期
- 如何使用jquery或javascript使用选定的下拉选项文本设置innerhtml
- JSColor 不适用于 Volusion 选项文本框
- 如何在 HTML 选择中对选项文本的某些部分使用不同的颜色
- 获取基于值的选择选项文本