【问题标题】:How can i detect DOM prepared and all attributes set我如何检测准备好的 DOM 和所有属性集
【发布时间】:2016-12-12 09:50:47
【问题描述】:

我有下一个 html 结构:

<div id="controls">    
    <div class="action" data-action="controller/action1" data-view="view1">...</div>
    <div class="action" data-action="controller/action1" data-view="view2">...</div>
    <div class="action" data-action="controller/action2" data-view="view1">...</div>
    <div class="action" data-action="controller/action2" data-view="view2">...</div>
     ...e.t.c.
</div>

在 typeScript 中,我尝试获取数据属性并构建 ajax 查询:

$('#controls').off('click').on('click','.action',(e) => {
       var $element = $(e.target),
            action = $element.data('action'),
            view = $element.data('view');

        if(!action)
            return this.sendNotification(false,'Setup action in config');
        if(!view)
            return this.sendNotification(false,'Setup view in config');

        // Ajax request and other logic 
});

我还有更新部分页面的功能(包括主题开头的 div 块)

private updateActionsBlock() {
   $.get(location.href, (html) => {
       $('#controls').html($(html).find('#controls'));
            this.init();
   });
}

问题

如果用户遇到 Internet 连接问题或计算机运行缓慢(可能是浏览器没有足够的 RAM)- 在使用 updateActionBlock() 几秒钟后无法从 $('.action') 获取数据属性。这些变得未定义。

问题

如何在 DOM 准备好之前禁止点击 $('.action');

希望可以不用setTimeout

【问题讨论】:

  • 要么仅在 document.ready 触发后运行updateActionsBlock(),要么隐藏元素并在 document.ready 上淡入。我看不出这实际上是你的问题,因为委托事件应该在 AJAX 请求完成之前绑定 long
  • 不幸的是我需要在.action点击处理每个ajax请求后使用updateActionBlockdocument.ready, document.DOMContentLoaded 仅在页面初始化中有效
  • 好的,但是我的意思是委托的事件处理程序已经绑定了,所以在没有触发事件的情况下无法单击元素。
  • 事件触发。但看起来目标元素没有数据属性。
  • 我无法复制:jsfiddle.net/k2432b4r。请注意,我确实必须手动将 active 类添加到元素中,因为您的示例中缺少该类

标签: javascript jquery dom typescript jquery-events


【解决方案1】:

问题不在 DOM 中。

$('#controls').off('click').on('click','.action',(e) => {
       var $element = $(e.target),
            action = $element.data('action'),
            view = $element.data('view');

        if(!action)
            return this.sendNotification(false,'Setup action in config');
        if(!view)
            return this.sendNotification(false,'Setup view in config');

        // Ajax request and other logic 
});

有时,当我点击.action 时,我在e.target 中有错误的元素。我获得了内部元素,而不是 &lt;div class='action'&gt;...&lt;/div&gt;

所以当我将 e.target 更改为 e.currentTarget 时,错误已修复。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-22
    • 1970-01-01
    • 2015-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-10
    • 1970-01-01
    相关资源
    最近更新 更多