JQuery - How to save and access an object in another object

I am trying to save an object as an attribute in another object, but cannot 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 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 were 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
source share
3 answers

Use data () instead of attr ();)

+1
source

Using the jQuery function attrsaves a variable as an attribute of an element. If you want to keep something more complex than a string, use.data

+1
source

, javascript, jquery, .data

+1

Source: https://habr.com/ru/post/1734875/


All Articles