views:

63

answers:

3

I am trying to store an object as an attribute in another object but can't seem to access it. Is it possible?

<script language="javascript">

  $(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

  });

</script>

<body>

<form id="form1" runat="server">
<div id="test">Here is a test div</div>
</form>

</body>

Answer: The guys below had it right

$(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!!


});
+1  A: 

Use data() instead of attr() ;)

Savageman
+1  A: 

Using the jQuery attr function stores the variable as an attribute on the element. If you want to store something a bit more complicated than a string, use .data

nickf
+1  A: 

attribute is intended to store text, not javascript object, using jquery you can use .data instead

mathroc