【问题标题】:jQuery append template?jQuery追加模板?
【发布时间】:2016-09-03 06:07:28
【问题描述】:

我正在尝试使用 jQuery 插入一些模板,并在使用时得到两个不同的结果:

一)

var $template = $("#productTemplate").html();

b)

var $template = $($("#productTemplate").html());

如果我使用 a) case 我可以多次添加模板,如果我使用 b) 我只能添加一次模板。 那么有什么区别呢?

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" href="style.css"/>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
    <script src="main.js"></script>
</head>

<body>


<div class="but">
    <a href="#" class="showForm"> Click </a>
</div>


<script id='productTemplate' type='text/template'>
    <div class="product">
        <h1>H1</h1>
    </div>
</script>

</body>
</html>

main.js

$(document).ready(function(){


    var $template = $($("#productTemplate").html());

    $(".showForm").on("click",function() {
        $("body").append($template);
    });

});

【问题讨论】:

    标签: javascript jquery html append


    【解决方案1】:

    在 (a) 中,$template 是一个字符串,.append($template) 在追加之前总是会基于该字符串创建一个新的 DOM 片段。

    在 (b) 中,$template 是一个对象,因为$(HTML_String) 返回jQuery,而.append($template) 将始终使用相同的对象——重新附加它会在 DOM 中移动它。要重用$template,您需要在附加之前显式地.clone()

    【讨论】:

      【解决方案2】:

      “我的猜测”:可能当您在点击处理程序之外加载 $template 对象时,jQuery 会识别您正在尝试附加相同的 jQuery 对象,然后 jQuery 不会附加。如果你再次加载你的变量,它会起作用:

      $(document).ready(function() {
        $(".showForm").on("click", function() {
          var $template = $($("#productTemplate").html()); //inside the click handler works
          $("body").append($template);
        });
      });
      

      Plunker:https://plnkr.co/edit/L19RGOKeQXYYkvOuBbX7?p=preview

      编辑:

      这两个选项之间的区别在于 b) 您可以像操作已存在的 DOM 元素一样操作,即您可以执行以下操作:

      $template.find("#my_hidden_id").val("12");
      $template.find("#another_div").append("<p>Another html</p>");
      

      然后附加您的新自定义模板...

      【讨论】:

        猜你喜欢
        • 2013-04-26
        • 2011-05-08
        • 1970-01-01
        • 2014-06-12
        • 2012-05-25
        • 2011-06-09
        • 2014-06-07
        • 2016-03-29
        • 2013-05-21
        相关资源
        最近更新 更多