[英]How do I store a jquery object on a HTML element property?
I have a <select>
form element where I create multiple <option>
children based on looping through a jQuery array of objects. 我有一个<select>
表单元素,在其中基于遍历对象的jQuery数组创建多个<option>
子级。
I want to store each jQuery associated with an <option>
on the <option>
itself, I guess as a property. 我想将与<option>
关联的每个jQuery存储在<option>
本身上,我想作为一个属性。 So that when I get the change event fired I can pull out the jQuery object which the <option>
was based on. 这样,当我触发change事件时,可以拉出<option>
所基于的jQuery对象。
I thought I could just set it using attr, serializing the object into JSON, but its not working. 我以为我可以使用attr进行设置,将对象序列化为JSON,但无法正常工作。 Any ideas? 有任何想法吗?
Here is some code: 这是一些代码:
// creating the select: (data is a jquery array of objects)
$(data).each(function() {
var opt = $('<option></option>').val(this[id_property]).html(this[label_property]);
// preserve the original jquery object on this <option> element:
opt.attr('json', JSON.stringify(this));
$(select).append(opt);
});
// bind the onchange event, and try to recreate that original jquery object
$(select).bind('change', function(event) {
// this gives me a ref to the <option> element:
var val = $(select).find(":selected");
// now how to get the original jquery object?
var item = $(val).attr('json');
});
I want that last line setting var item to the original jquery object - or somehow recreate it. 我希望将var项目设置为原始jquery对象的最后一行-或以某种方式重新创建它。 I even tried doing an eval()
passing in item since it is JSON formatted but it throws an error. 我什至尝试做一个eval()
传递项目,因为它是JSON格式,但会引发错误。
您可以利用jQuery中的data()
方法,这可能会为您带来最有利的结果,并且使您能够避免不必要的自定义序列化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.