Uncaught TypeError: Cannot read property 'substr' of undefined Dustjs

Uncaught TypeError: Cannot read property 'substr' of undefined Dustjs

我正在尝试学习 javascript 模板,即 dustjs,但我遇到了我认为非常基本的问题,甚至 google 也无法回答 :)

这是最简单形式的代码

      <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 行)。

渲染模板时,用渲染的模板替换 <ul class="vodka"> 的内容。

但是,无论出于何种原因,您也将模板源放在了这个容器中。模板源在第一次渲染时从 DOM 中移除,因为它已被渲染的内容替换。因此,当您尝试第二次呈现模板时,此行将 source 设置为 null:

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

Dust 出错是因为它正在尝试将 null 编译为模板。