【问题标题】:Cacheing the DOM and binding click events on elements that are not rendered yet缓存 DOM 并在尚未呈现的元素上绑定点击事件
【发布时间】:2017-08-04 01:10:28
【问题描述】:

“稳定的应用开发需要严格的代码组织 进入明确的‘块’。”

为此,我使用 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));

现在假设我想将点击事件绑定到 Mustache 模板中的元素或缓存我稍后将使用的元素...我显然不能在页面加载时执行此操作,因为模板尚未呈现。

为了让事件生效,我必须在渲染 HTML 之后声明一个事件。要使用一个元素,我必须在需要时手动选择它,例如$('.foo') 而不是缓存的this.foo

结果是现在我的对象中散布了 on('click) 事件和 jQuery 选择,而不是 bindEvents 和 cacheDOM 函数。

这是一个问题的简化示例:https://jsfiddle.net/6L2ry6hr/

在上面的例子中,它还不错......但随着我的应用程序变得越来越复杂,它变得有点麻烦。

【问题讨论】:

标签: javascript jquery html caching template-engine


【解决方案1】:

现在假设我想将点击事件绑定到 Mustache 中的元素 模板

我显然不能在页面加载时这样做,因为模板尚未呈现。

使用 jQuery 可以满足要求。 &lt;script&gt; 元素的 .innerHTML 可以传递给 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
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-16
    • 2022-12-14
    • 1970-01-01
    相关资源
    最近更新 更多