2010-03-01 117 views
3

In an earlier question我制定瞭如何將object作爲properties存儲。 現在我要當object通過事件傳遞給訪問這些properties但無法得到它的工作:jQuery - 從傳遞給事件的另一個對象中訪問對象屬性

<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 
    var test; 
    test = $('#test');//the div 
    jQuery.data(test, "obj", testObject); 

    //prove it worked and the TestObject is assigned 
    alert(jQuery.data(test, "obj").testProperty);//works 

    $('#test').click(TestClick); 
    //test.click(TestClick); doesn't work either 

    function TestClick() { 
     alert($(this).attr("id"));//displays "test" - works 
     alert(jQuery.data($(this), "obj").testProperty); 
     //testProperty is null or not an object?? 
     //clearly TestObject is no longer attached to the div, why? 
     //Or have I attached it the wrong way?  
     //alert(jQuery.data(this, "obj").testProperty); doesn't work either 
    }; 
}); 
</script> 
<body> 
    <form id="form1" runat="server"> 
     <div id="test">Here is a test div</div> 
    </form> 
</body> 

回答

2

這會爲你工作,其附加到元素,而不是作爲一個參考這似乎稍微改變元素(這是一個不同的.data()電話,see here for info):

$(document).ready(function() { 
    function TestObject() { 
    this.testProperty = "green"; 
    } 

    var testObject = new TestObject(); 
    var test = $('#test').data("obj", testObject); 

    alert(test.data("obj").testProperty); 

    $('#test').click(TestClick); 
    function TestClick() { 
    alert($(this).attr("id")); 
    alert($(this).data("obj").testProperty); 
    }; 
}); 
1
//clearly TestObject is no longer attached to the div, why? 

因爲this回報你的函數情況下在該行alert(jQuery.data($(this), "obj").testProperty);您應該使用alert(jQuery.data($("#test"), "obj").testProperty);代替。

+0

這也行不通,在'jQuery.data()'你存儲的DOM元素的引用仍然不一樣...在正常情況下,你不應該使用'jQuery .Data()',而是'.data()'。 – 2010-03-01 12:54:57