我在脚本标签中使用模板。在javascript"class"中,我首先声明了我将使用的所有元素。如果从模板添加某些元素 - 它们将不起作用。
<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/那么如何在加载之前声明所有可能的元素呢?
我不知道你的确切要求,但你实际上可以试试这个:
var $el = '',
goBtn = $('#go'),
$container = $('#container'),
newTpl = $('#new');
goBtn.on('click', function(){
$container.html(newTpl.html());
$el = $('#el'); //redefining $el variable
alert($el.length);
});
小提琴:
https://jsfiddle.net/hfhLpuc3/2/
不能以这种方式定义全局变量,但事件处理程序可以绑定:
$(document).on("click", "#go", function() {
...
});
如果之后添加 #go 标记,它将起作用事件。