1

问题:我正在通过 JS 模板系统创建一个元素。在该模板中,我指定了一个 ID。创建该 ID 后,jQuery 是否有办法在创建特定元素时触发回调?

带有 Knockoutjs 的示例 JS/HTML:

function Dialogs(){
    this.createDialog = function(id){
        //alert('creating dialog');
        // If i add a setTimeout here, it will work.
            $("#" + id).dialog({
                autoOpen: true,
                resizable: false,
                width: 360,
                height: 200,
                dialogClass: 'systemError',
                modal: true,
                closeText: 'hide'
            });


    };
    this.data = ko.observableArray([
        new Dialog("Demo", 'htmlContent', { 
            id: 'testDialog',
            success: function() {}, 
            error: function(){},
            actions:[
                new DialogAction('continue', { 
                    className: 'foo', 
                    id: 'bar',
                    events: { 
                        click: function() { 
                            console.log('do stuff');
                        }
                    }
                })
            ] 
        })

    ]);
}
function Dialog (name, htmlContent, options) {
    options = options || {};
    this.id = options['id'] || '';
    this.name = ko.observable(name || "");
    this.className = options['className'] || '';
    this.htmlContent = ko.observable( htmlContent || "");
    this.successCallback = options['success'] || this.close;
    this.errorCallback = options['error'] || this.throwError
    this.actions = options['actions'] || [];
}

function DialogAction (name, options) {
    options = options || {};
    this.name = ko.observable(name || "");
    this.className = options['className'] || null;
    this.id = options['id'] || null;
    this.successCallback = options['success'] || null;
    this.errorCallback=  options['error'] || null;

}
ko.applyBindings(new Dialogs());

的HTML:

<div id="dialog-holder" data-bind="foreach: Dialogs.data()">
      <div class="systemErrorDialog" data-bind="template: { name: 'dialog-system-error', data: $data, afterRender: Global.Dialogs.createDialog($data.id) }"></div>
</div>

<script type="text/template" id="dialog-system-error">
    <div data-bind="html:htmlContent(), attr:{id: id, class:className,title:name()}">
      <div class="actions" data-bind="foreach: actions"> 
        <div data-bind="attr:{id: name(), class: className}"></div>
      </div> 
    </div>
</script>
4

1 回答 1

1

您可以运行一个时间间隔来检查 dom 中的 id,然后在它存在时触发一个事件。

var intv = setInterval(function(){
 var $el = $("#myId");

 if ( $el.length > 0 ) {
   clearInterval(intv);
   doSomething();
 }
}, 500);

如果从未显示,可能应该在事件 10 秒后清除间隔:

setTimeout(function(){
  clearInterval(intv);
}, 10000);
于 2012-11-14T22:52:43.703 回答