Material Design Lite JS不适用于动态加载的HTML文件

问题描述:

我想统一我网站的导航布局,所以我创建了一个单独的html文件,其中包含导航代码。我使用JS动态加载文件:

I want to unify the navigation layout for my website, so I created a separate html file that holds the code for the navigation. I use a JS to load the file dynamically:

$("#navigation").load("/navigation/navigation.html", function() {
   $.getScript('/material.min.js');
});

问题在于material.min.js没有为这个动态加载的组件执行HTML和我失去了一些关键的功能。我如何解决这个问题?

The problem is that the material.min.js does not get executed for the dynamically loaded components inside this html and I lose some crucial functionality. How do I fix that?

检查 componentHandler 是否已加载,并尝试升级元素后加载。

Check if the componentHandler is loaded, and try to upgrade the elements after load.

if(!(typeof(componentHandler) == 'undefined')){
  componentHandler.upgradeAllRegistered();
}

组件处理程序的工作方式

How the Component Handler works


总之,这遍及所有注册的组件。使用提供的CSS类查询所有节点。循环播放并逐个实例化它们。在节点上完成升级时,升级的对象将添加到数据集中。此对象包含逗号分隔的组件列表 classAsString 属性,以确定哪些升级已完成。

In short this goes over all registered components. Queries for all nodes with the provided CSS class. Loops over those and instantiates them one-by-one. When the upgrade is done on a node, the upgraded object is added to the dataset. This object contains a comma separated list of component classAsString properties to identify which upgrades have been done.