2010-06-19 105 views
0

在Firebug控制檯中工作,但不是從文件中工作。未初始化jQuery擴展功能

谷歌瀏覽器 - 遺漏的類型錯誤:對象#有沒有方法 'listAttributes'

火狐 - $(」 DIV4" 。)listAttributes不是一個函數

<script src='/jquery.js'></script> 
<script src='jquery.listAttributes.js'></script> 

<div class='div4' style='color:red;'> 
</div> 

<script> 
$(".div4").listAttributes(); 
</script> 

jquery.listAttributes.js:

if(jQuery) { 
    jQuery(document).ready(function() { 
     jQuery.fn.listAttributes = function(prefix) { 
      var list = []; 
      $(this).each(function() { 
       console.info(this); 
       var attributes = []; 
       for(var key in this.attributes) { 
        if(!isNaN(key)) { 
         if(!prefix || this.attributes[key].name.substr(0,prefix.length) == prefix) { 
          attributes.push(this.attributes[key].name); 
         } 
        } 
       } 
       list.push(attributes); 
      }); 
      return (list.length > 1 ? list : list[0]); 
     } 
    }); 
} 

我的錯誤在哪裏?

回答

4

此代碼:

$(".div4").listAttributes(); 

document.ready運行前,但你的插件沒有定義直到document.ready,只是從你的插件:)


刪除jQuery(document).ready(function() { });包裝另請注意,對插件的呼叫應爲必須在document.ready處理,像這樣:

$(function() { 
    $(".div4").listAttributes(); 
}); 

這確保了.div4元素在DOM,並準備去。

1

您在腳本中調用$(".div4").listAttributes();在線(所以當瀏覽器解析是<script>元素故稱),但你是一個ready事件中分配jQuery.fn.listAttributes所以它不存在,直到後的瀏覽器已經完成解析整個文件。

+0

是的,就是謝謝 – 57ar7up 2010-06-19 11:50:59