0

我努力學習JavaScript模板,即dustjs的特性「SUBSTR」,但我遇到的問題,我認爲這是如此基本的甚至是Google不能回答吧:)遺漏的類型錯誤:無法讀取未定義Dustjs

這裏是代碼這是最簡單的形式

 <button class="getData" onClick="clicker()">Get Data</button> 

     <ul class="vodka"> 
     <script id="vodka" type="text/x-template"> 

     <li>{name}</li> 

     </script> 
     </ul> 

的Javascript

window.addEventListener("load", clicker) 

function clicker() 
{ 
    getData(); 
} 

function getData() 
{ 
var data = {name:"Vodka", degree:97} 
var source = $("#vodka").html(); 
var template = dust.compile(source, "vodkaTemplate"); 
dust.loadSource(template); 
dust.render("vodkaTemplate", data, function(err, res){ 
      $(".vodka").html(res) 
      console.log(res) 
}) 
} 

在初始化過程中模板呈現完美,但點擊按鈕會導致錯誤

Uncaught TypeError: Cannot read property 'substr' of undefined

我在做什麼錯?

+1

請在codepen,plunkr,jsbin或類似網站上提供一個運行示例。 – 2015-02-23 15:43:19

+0

這裏,但jsbin一直拋出奇怪的錯誤 [鏈接](http://jsbin.com/yukojutumo/1/edit?html,console,output) – 2015-02-23 16:03:44

回答

0

您在加載時(腳本的第1行)呈現模板一次。

當您渲染模板時,將<ul class="vodka">的內容替換爲呈現的模板。

但是,無論出於何種原因,您都已將模板源放置在此容器中。模板源在第一次渲染時從DOM中被移除,因爲它被渲染的內容所取代。所以,當你嘗試呈現模板中的第二次,這條線將sourcenull

var source = $("#vodka").html(); // #vodka does not exist anymore 

和塵埃的錯誤,因爲它試圖編譯null爲模板。

相關問題