[英]code to set a select box option value as an object
in an html page i have got, i have a select box like this with values. 在我有一个html页面,我有一个这样的选择框与值。
<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. 我想传递一个javascript数组或对象作为选项值。 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. 填充函数中的this.value.name,this.value.age。
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+ 您将无法在value
属性中存储对象/数组,但是可以选择使用jQuery 1.4.3+自动支持json的data-*
属性
<select>
<option data-value='{"name":"rajiv","age":"40"}'>a</option>
<option data-value='{"name":"mithun","age":"22"}'>f</option>
</select>
And using .change()
并使用.change()
$("select").change(function(){
alert($(this).find(":selected").data("value").age);
});
No, not just like that. 不,不只是那样。 Values have to be strings. 值必须是字符串。 I'd strongly recommend to use something like jQuerys .data()
method to hold Arrays
or Objects
in an expando property. 我强烈建议使用类似jQuerys .data()
方法的东西来保存expando属性中的Arrays
或Objects
。
If it must be in the value, you just need to JSON decode (.parse) it: 如果它必须在值中,你只需要JSON解码(.parse)它:
var myValue = JSON.parse(this.value);
myValue.age; // 40
myValue.name // rajiv
But again, I don't think this is a good solution. 但同样,我认为这不是一个好的解决方案。 Have a look at http://api.jquery.com/jQuery.data/ Also, jQuery will automatically convert Arrays and Objects if you put the JSON strings in any data-
HTML5 attribute. 看看http://api.jquery.com/jQuery.data/如果你把JSON字符串放在任何data-
HTML5属性中,jQuery会自动转换Arrays和Objects。 For instance: 例如:
<option value="A" data-info="{'name':'rajiv',age:'40'}">something</option>
If you access that node with jQuery now, we automatically got that object in it's data expando 如果您现在使用jQuery访问该节点,我们会自动在其数据expando中获取该对象
$('option').data('info').name; // === rajiv
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.