2012-05-28 30 views
0

我寫了一個jQuery插件,需要添加.data()插件內的元素,並在稍後檢索。當我的元件上運行該方法通過它的id等引用元件時,無法檢索所存儲的數據:

$('#name_of_the_element') 

如果我參考使用$(this)元件我可以訪問數據。

我在做什麼錯?

這裏的jQuery插件的代碼和HTML文件的代碼,我用它:

jQuery插件:

(function($){ 

    var methods = { 

     checkit : function(options) { 

      return this.each(function(){ 

       var $this = $(this); 

       $this.data('testdata','this is what i need to see'); 

      }); 
     } 


    } 

    $.fn.demoplug = function(method) {   
    if (methods[method]) { 
     return methods[ method ].apply(this, Array.prototype.slice.call(arguments, 1)); 
    } else if (typeof method === 'object' || ! method) { 
     return methods.checkit.apply(this, arguments); 
    } else { 
     $.error('Method ' + method + ' does not exist on jQuery.antigravity'); 
    }  

    }; 

})(jQuery); 

HTML文件:

<div role="main" id="main"> 
    <ul id="miniatures"> 
     <li><img src="img/thumbs/thumb-01.jpg"></li> 
     <li><img src="img/thumbs/thumb-02.jpg"></li>    
     <li id="mov3"><img src="img/thumbs/thumb-03.jpg"></li> 
     <li><img src="img/thumbs/thumb-04.jpg"></li>    
     <li><img src="img/thumbs/thumb-05.jpg"></li> 
    </ul> 
</div> 

<script src="js/libs/jquery-1.7.2.min.js"></script> 
<script src="js/libs/jquery.demoplug.js"></script> 
<script> 

    $(document).ready(function(){ 

     $('li#mov3').demoplug('checkit'); 

     alert($('li#mov3').data('checkit')); // not working 

     $('li#mov3').click(function(){ 

      alert($(this).data('testdata')); // works 

     }); 
    }); 

</script> 
+1

從我所看到的,這只是因爲沒有數據附加稱爲'checkit'。 – ahren

回答

1
alert($('li#mov3').data('checkit')); // not working 

這是因爲您正在提取數據中的「checkit」鍵,但您將該鍵設置爲「testdata」:

$this.data('testdata','this is what i need to see'); 

它改變這會工作:

alert($('li#mov3').data('testdata')); 
+0

謝謝你snjoetw,當我看到那個......;) – Greg

0

啊,錯誤是在錯誤的地方!我從我正在處理的插件中提取此代碼以顯示我認爲錯誤的地方,但真正的錯誤是我在使用.clone()方法和錯誤的.c​​lone()方法使用插件發生這個錯誤 - 它將LI元素的ID加倍,這樣我得到了2個id =「mov3」的LI。我沒有閱讀足夠的文檔來查看使用.clone()時克隆的內容。謝謝你們的回答!

相關問題