代码将选择框选项值设置为对象 [英] code to set a select box option value as an object

查看:172
本文介绍了代码将选择框选项值设置为对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个html页面中,我有一个像这样的值的选择框。

 < select onChange =return filler(this.value);> 
< option value ={'name':'rajiv',age:'40'}> a< / option>
< option value ={'name':'mithun',age:'22'}> f< / option>
< / select>

我想传递一个javascript数组或对象作为选项值。
现在它将选项值视为一个字符串。

我希望它是一个数组,以便我可以通过它来访问它。



this.value.name,this.value.age在填充函数中。



可能吗?

$你不能在属性中存储对象/数组,但是选项将使用jQuery 1.4.3 +自动支持json的 data - * 属性

 <选择> 
< option data-value ='{name:rajiv,age:40}'> a< / option>
< option data-value ='{name:mithun,age:22}'> f< / option>
< / select>

并使用 .change() $ b

 $(select)。选择)。data(value)。age); 
});

jsfiddle示例

in an html page i have got, i have a select box like this with values.

<select onChange="return filler(this.value);">
<option value="{'name':'rajiv',age:'40'}">a</option>
<option value="{'name':'mithun',age:'22'}">f</option>
</select>

i want to pass a javascript array or object as the option value. right now it is treating the option value as a string.

i want it to be an array so that i can access it by

this.value.name,this.value.age in the filler function.

is this possible?

解决方案

You will not be able to store objects/arrays in the value attribute, however an option would be to use data-* attributes which supports json automatically with jQuery 1.4.3+

<select>
    <option data-value='{"name":"rajiv","age":"40"}'>a</option>
    <option data-value='{"name":"mithun","age":"22"}'>f</option>
</select>

And using .change()

$("select").change(function(){
    alert($(this).find(":selected").data("value").age);
});

Example on jsfiddle

这篇关于代码将选择框选项值设置为对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆