我有一个简单的模板设置,如下所示:
<script id="entry" type="text/x-handlebars-template">
<p>Some content</p>
<h2>Language Select:</h2>
<button type="button" class="btn btn-primary">English</button>
<h2>Ready:</h2>
<button type="button" id="play" class="btn btn-success">Play</button>
<button type="button" id="stop" class="btn btn-danger">Stop</button>
</script>
但是,在我的文档中,我也有一个脚本,其内容如下:
var playButton = document.querySelector('#play');
playButton.addEventListener('click', function (e) {
sendMessage('Cue', 'Play');
}, false);
在大多数情况下(但并非总是如此),由于javascript的异步特性,它返回:
Uncaught TypeError: Cannot read property 'addEventListener' of null
如果我以setTimeout
一定数量包装该代码,它将始终有效。
有人可以向我解释将事件侦听器从脚本添加到生成的模板内容的最佳方法吗?
我看着这个答案,但似乎他们建议的方法只是在添加事件侦听器之前添加延迟。
抱歉,忘记我以前的回答。
首先需要渲染模板,然后将此html插入正文...
var source = document.querySelector("#some-template").innerHTML;
var template = Handlebars.compile(source);
document.body.innerHTML = template();
然后添加侦听器...
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句