我正在尝试将对象存储为另一个对象中的属性,但似乎无法访问它。 有可能吗?
<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!!
});
答案 0 :(得分:1)
使用data()而不是attr();)
答案 1 :(得分:1)
使用jQuery attr
函数将变量存储为元素的属性。如果要存储比字符串更复杂的内容,请使用.data
答案 2 :(得分:1)
属性用于存储文本,而不是javascript对象,使用jquery可以使用.data代替