jQuery – 如何在另一个对象中存储和访问对象

我试图将对象存储为另一个对象中的属性,但似乎无法访问它。 可能吗?

 $(document).ready(function() { //create a TestObject function TestObject() { this.testProperty = "green"; } //and an instance of it var testObject = new TestObject(); //attach this instance to the div as a property //if it could be attached another way perhaps that's the answer?? $('#test').attr("obj", testObject); alert(testObject.testProperty);//works - obviously alert($('#test').attr("obj").testProperty); //does not work var o = $('#test').attr("obj"); alert(o.testProperty); //does not work });   
Here is a test div

答:下面的人说得对

 $(document).ready(function() { //create a TestObject function TestObject() { this.testProperty = "green"; } //and an instance of it var testObject = new TestObject(); //attach this instance to the div as a property var test; test = $('#test'); jQuery.data(test, "obj", testObject); alert(testObject.testProperty); //works - obviously alert(jQuery.data(test, "obj").testProperty); //works!! }); 

使用data()而不是attr();)

使用jQuery attr函数将变量存储为元素的属性。 如果要存储比字符串更复杂的东西,请使用.data

attribute用于存储文本,而不是javascript对象,使用jquery可以使用.data