"Stable application development requires strict organizing of code into clear 'blocks'."
为此,我使用 Mustache 将脚本中的数据渲染到 HTML 中。
我将我的 Mustache 模板存储在特殊的脚本标签中:
<script id="template" type="text/template">
Mustache template goes here and is invisible
</script>
要在 div
中渲染模板,我只需调用 Mustache 渲染函数
var template = $('#template').html();
$('#someDiv').html(Mustache.render(template));
现在假设我想将单击事件绑定(bind)到 Mustache 模板中的元素或缓存稍后将使用的元素...我显然无法在页面加载时执行此操作,因为模板尚未呈现。
为了让事件正常工作,我必须在渲染 HTML 后声明一个事件。要使用某个元素,我必须在需要时手动选择它,例如$('.foo')
而不是缓存的 this.foo
结果是,现在我的 on('click) 事件和 jQuery 选择遍布在我的对象中,而不是在 bindEvents 和 cacheDOM 函数中。
这是一个带有问题简化示例的 fiddle :https://jsfiddle.net/6L2ry6hr/
在上面的示例中,这还不错......但随着我的应用程序变得越来越复杂,它变得有点麻烦。
最佳答案
Now imagine I want to bind a click event to an element in a Mustache template
I obviously can't do that on page load because the template is not rendered yet.
使用 jQuery 可以满足该要求。 .innerHTML
的<script>
元素可以传递到 jQuery()
附加了事件和事件处理程序。
jQuery.holdReady(true);
var template = jQuery($("#template").html());
// template.filter("element").on("event", function() {// do stuff})
jQuery("body").append(template);
jQuery.holdReady(false);
jQuery(function() {
// do stuff
})
关于javascript - 缓存 DOM 并在尚未渲染的元素上绑定(bind)点击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42773455/