【问题标题】:MDL ready eventMDL 就绪事件
【发布时间】:2016-05-31 05:10:40
【问题描述】:

MDL 在页面加载时升级其组件,因此带有autofocus 属性的<input> 失去了焦点。我想在 MDL 完成重新渲染后将此输入设置为焦点。

我正在尝试收听某些页面 ready 事件 (codepen):

$('input#srch').one('componentDidUpdate', function(){console.log('ready')});

不适用于 $(document)$(document.body)$('.mdl-layout') 选择器。
我搜索了一些类似的事件,但没有运气,我错过了什么吗?
当然我可以使用setTimeout,但我认为这不应该是一个解决方案????

【问题讨论】:

    标签: jquery material-design jquery-events material-design-lite autofocus


    【解决方案1】:
    /* Check if the material design has finished the rendering */
    
    var mdlLoaded = setInterval(function(){ 
        if(typeof document.querySelector('.mdl-js-layout') !== 'undefined') init()
    }, 100)
    
    function init () { 
        clearInterval(mdlLoaded)
        alert('ready')
    }
    

    【讨论】:

      【解决方案2】:

      您可以在布局元素.mdl-ayout 上监听mdl-componentupgraded 事件。

      $(document).ready(function() {
          $('.mdl-layout').on('mdl-componentupgraded', function(e) {
              if ($(e.target).hasClass('mdl-layout')) {
                  alert('ready');
              }
          });
      });
      

      使用on 代替one。您的页面可能有多个正在升级的元素。通过使用one,您将只获得第一次升级。使用on,由于事件冒泡,处理程序将被多次调用。勾选e.target对布局元素的具体升级做出反应。

      使用$(document).ready() 回调。在将处理程序附加到其元素之前等待 DOM 准备就绪。否则$('.mdl-layout') 选择器可能不匹配并且事件处理程序可能不会附加。

      【讨论】:

      • 使用 firefox,mdl-componentupgraded 调用仅在我加载页面后进行,然后刷新它......你知道为什么会这样吗?适用于 Chrome
      【解决方案3】:

      我相信你可以收听mdl-componentupgraded 事件:

      $('input#srch').bind('mdl-componentupgraded', function(){console.log('ready')});
      

      【讨论】:

        猜你喜欢
        • 2011-07-20
        • 1970-01-01
        • 2011-12-04
        • 2020-05-30
        • 2016-12-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多