2012-07-21 77 views
0

有沒有辦法讓一個函數內的元素被設置爲一個元素的'數據'的對象?如果沒有,那麼有什麼替代方法可以實現呢?jQuery的 - 如何獲取數據對象函數內的元素

var m = function(options){ 
    // Some initialization code here 
} 

m.prototype.doSomething: function() { 
    // How do i get the #an_element here? 
} 

$("#an_element").data('myObject', m); 

回答

0

最簡單的方法是把它給給構造函數,你可以在jsfiddle上檢查它。

var m = function(options){ 
    // Some initialization code here 
    $.extend(this, options); 
} 

m.prototype.doSomething= function() { 
    // How do i get the #an_element here? 
    var _this=this; 
    if(_this.el && _this.el.length){ 
     _this.el.css({color:"black"}); 
    } 
} 
$(function(){ 
    var $el=$("#an_element"); 
    $el.data('myobject', new m({el:$el})); 
    $el.click(function(){ 
     var nn=$(this).data("myobject"); 
     nn.doSomething(); 
     return false; 
    }); 
}); 

你做了什麼,那就是你想投入到數據本身的功能,但你必須之前創建一個對象像這樣的錯誤:$("#an_element").data('myObject', new m());

+0

我試圖找到一種方法來避免必須將元素傳遞給構造函數。 – arvinsim 2012-07-22 04:33:18

0

我假設你在#an_element中存儲了一個類或id,即選擇器。試試這個:

var m = function(options){ 
    // Some initialization code here 
} 

m.prototype.doSomething: function() { 
    var selector = $("#an_element").data('myObject'); 
    var required_element = $(selector); 
} 

$("#an_element").data('myObject', m); 
+0

我不認爲這會工作,如果選擇器返回多個元素 – arvinsim 2012-07-22 04:32:22