gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 08:27:53 24 4
gpt4 key购买 nike

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

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

答案:下面的人说得对

$(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 - 如何在另一个对象中存储和访问一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2355550/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com