0

I use templates in script tags. In javascript "class" first i'm declaring all elements I will work with. And if some elements will be added from template - they wont work.

<script type="text/template" id="new">
    <div id="el">Yo</div>
</script>

<div id="container">
    <button id="go">Paste here</button>
</div>

var $el = $('#el'),
goBtn = $('#go'),
$container = $('#container'),
newTpl = $('#new');

goBtn.on('click', function(){
  $container.html(newTpl.html());
  alert($el.length); // return 0!
});

https://jsfiddle.net/0fat5htg/ So how to declare all possible elements before they are loaded?

Sergey Kudryashov
  • 713
  • 2
  • 9
  • 30

2 Answers2

0

I don't know exactly your requirements, but you can actually try this:

var $el = '',
    goBtn = $('#go'),
    $container = $('#container'),
    newTpl = $('#new');

goBtn.on('click', function(){
  $container.html(newTpl.html());
  $el = $('#el'); //redefining $el variable 
  alert($el.length);
});

Fiddle:

https://jsfiddle.net/hfhLpuc3/2/

Mário Areias
  • 411
  • 4
  • 7
0

You can't define the global variables this way, but the event handler can be bound with:

$(document).on("click", "#go", function() {
...
});

It will work event if the #go markup is added afterwards.

Maurice Perry
  • 32,610
  • 9
  • 70
  • 97