2011-11-03 46 views
2

我怎樣才能解決這個錯誤:我該如何解決「無方法‘appendTo’錯誤

遺漏的類型錯誤:對象沒有方法‘appendTo’ 下面的代碼:

function refresh(){ 
     $('#contacts').empty(); 
     $("#contactTmpl").tmpl({contacts:contacts}).appendTo("#contacts"); 
     $(".contact").each(function(i) { 
      var contact = contacts[i]; 
      $("input.tomap", this).link(contact); 
     }); 
    } 


<script type="text/javascript" src="a.js"></script> 

<form> 
    <div id="contacts">Loading ...</div> 
    <button class="add">New</button> 
    <button class="save"> Save</button> 
</form> 
<script id="contactTmpl" type="text/x-jquery-tmpl"> 

    {{each contacts}} 
     <div class="contact" data-index="${$index}"> 
      <label>First name</label> <input class="tomap" name="firstName" value="${firstName}"> 
      <label>Last name</label> <input class="tomap" name="lastName" value="${lastName}"> 
      <label>Number</label> <input class="tomap" name="phone" value="${phone}"> 
      <div class="tools"> 
       <button class="delete"</button> 
      </div> 
     </div> 
    {{/each}} 
</script> 

這是HTML和JavaScript代碼

+0

沒有什麼明顯的錯誤與你在這裏包含的內容。什麼是refresh()被調用?文件準備好或加載後,我希望。 a.js裏面有什麼?也許你可以扔一個小提琴看? – Kato

回答

1

您需要先創建節點試試這個:

$('<div id="contactTmpl"/>').tmpl({contacts:contacts}).appendTo("#contacts"); 
+0

我有節點,請參閱我所做的編輯 –

4

我會假設你正在使用jQuery模板,因爲這是它的樣子。如果模板未能呈現,那麼它返回null,我相信這就是爲什麼你得到的對象沒有方法錯誤。我將您的代碼修剪到模板和調用模板,並修復了{{each}}${$index}。我還假設變量contacts是一個對象數組。

的工作小提琴是在這裏:http://jsfiddle.net/brettwp/yfcuL/

而且代碼:

<div id="contacts">EMPTY</div> 
<script id="contactTmpl" type="text/x-jquery-tmpl"> 
    {{each(index,contact) contacts}}  
     <div class="contact" data-index="${index}"> 
      <label>First name</label> <input class="tomap" name="firstName" value="${contact.firstName}"> 
      <label>Last name</label> <input class="tomap" name="lastName" value="${contact.lastName}"> 
      <label>Number</label> <input class="tomap" name="phone" value="${contact.phone}"> 
      <div class="tools"> 
       <button class="delete"></button> 
      </div> 
     </div> 
    {{/each}} 
</script> 

$(function(){ 
    $("#contactTmpl").tmpl({contacts: contacts}).appendTo("#contacts"); 
}); 
相關問題