0

我们先来写代码:

$(function(){

   //Step-2) Load and a template from server and APPEND to BODY  
   function loadTemplate(path, callback) {
        $.get(path, null, function (t) {
            $('body').append(t);
        }, 'text');

        if (callback != undefined && typeof (callback) == 'function') {
            callback.apply(window);
        }
    }

    //Step-3) a callback method
    function showProduct() {
        //setTimeout(function () {
        //    $('#prodBasicView').tmpl(prod).appendTo('#prodView');
        //}, 100);

        alert($('#prodBasicView').length); // it alerts 0, But I am expecting 1

    }

    //Step-1) initiating loading template
    loadTemplate('/template/remote-template2.htm', showProduct);
});

远程模板2.htm:-

     <div id="prodBasicView" style="display:none;">
       <div class="myProd">
        <h3> Product Name</h3>
           <span>Price: $ 700 </span>
       </div>
     </div>

问题:

  • loadTemplate方法成功加载了一个模板 ( remote-template2.htm ) 并附加到正文。
  • 成功加载模板后,将触发传递的回调函数showProduct方法。
  • showProduct方法中,我尝试使用加载的模板($('#prodBasicView')),但它返回空数组。
  • 但是,如果我将showProduct的执行延迟几毫秒,它可以工作,但我认为这不是一个好习惯
  • 以上点似乎是附加的DOM元素还没有准备好

  • 如何确保修改/操作的 DOM 在使用它们之前再次准备好?

4

2 回答 2

1

在我看来,您只需要将回调调用代码放在$.get回调中,如下所示:

function loadTemplate(path, callback) {
    $.get(path, null, function (t) {
        $('body').append(t);
        if (callback != undefined && typeof (callback) == 'function') {
            callback.apply(window);
        }
    }, 'text');
}
于 2012-08-09T05:10:48.373 回答
1

callback在 ajax 回调处理程序中执行你的。(因为 ajax 是异步工作的)

   function loadTemplate(path, callback) {
        $.get(path, null, function (t) {
            $('body').append(t);
            if (callback != undefined && typeof (callback) == 'function') {
               callback.apply(window);
            }
        }, 'text');
    }
于 2012-08-09T05:11:11.877 回答