簡體   English   中英

緩存DOM並將click事件綁定到尚未渲染的元素上

[英]Cacheing the DOM and binding click events on elements that are not rendered yet

“穩定的應用程序開發需要嚴格地將代碼組織成清晰的“塊”。”

為此,我正在使用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));

現在想象一下,我想將click事件綁定到Mustache模板中的元素,或者將以后將要使用的元素緩存起來……由於頁面模板尚未呈現,我顯然無法在頁面加載時執行該操作。

為了使事件生效,我僅渲染HTML 之后才聲明一個事件。 要使用一個元素,我必須在需要時手動選擇它,例如$('.foo')而不是緩存的this.foo

結果是現在我在整個對象中散布了on('click)事件和jQuery選擇,而不是在bindEvents和cacheDOM函數中。

這是一個帶有問題簡化示例的小提琴: https : //jsfiddle.net/6L2ry6hr/

在上面的示例中,這還不錯...但是隨着我的應用程序變得越來越復雜,它變得有些麻煩。

現在想象一下,我想將click事件綁定到Mustache模板中的元素

我顯然無法在頁面加載時執行此操作,因為模板尚未呈現。

使用jQuery可以滿足要求。 可以將<script>元素的.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
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM