代码之家  ›  专栏  ›  技术社区  ›  user180574

车把:为什么这个代码不起作用?

  •  0
  • user180574  · 技术社区  · 7 年前

    我是新手,觉得基础教程不是很新手友好。我必须将各个部分组合在一起,下面的代码似乎不起作用。HTML是正确生成的,这意味着它可以工作,但没有显示任何内容。

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <title>test handlebars</title>
    <meta charset="UTF-8">
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.js"></script>
    
    <script id="entry-template" type="text/x-handlebars-template">
      <div class="entry">
        <h1>{{title}}</h1>
        <div class="body">
          {{body}}
        </div>
      </div>
    </script>
    
    </head>
    <body>
    <div class="container"></div>
    
    <script>
    $(document).ready(function(){
      var source = $("#entry-template").html();
      var template = Handlebars.compile(source);
      var context = {title: "My New Post", body: "This is my first post!"};
      var html = template(context);
      console.log(html);
      $(".container").innerHTML = html;
    });
    </script>
    
    </body>
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   AuxTaco    7 年前
    $(".container").innerHTML = html;
    

    您混合了香草JS和jQuery。要么将HTML设置为普通方式,

    document.querySelector(".container").innerHTML = html;
    

    或jquery方式:

    $(".container").html(html);