Jquery add template?

I am trying to insert some kind of template with jQuery and get two different results when using:

a)

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

b)

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

If I use a) case, I can add a template many times, if I use b) I can add a template only once. So what is the difference?

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);
    });

});
+4
source share
2 answers

In (a) $templateis a string, and .append($template)will always create a new DOM fragment based on the string before adding.

(b) $template - , $(HTML_String) jQuery, .append($template) - DOM. $template, .clone() .

+3

" ": , $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

EDIT:

, b) DOM, .. - :

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

...

+1

All Articles