Material Design Lite JS not applied to dynamically

2019-02-06 11:58发布

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');
});

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?

2条回答
走好不送
2楼-- · 2019-02-06 12:17

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

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.

查看更多
孤傲高冷的网名
3楼-- · 2019-02-06 12:25

From the official docs:

Material Design Lite will automatically register and render all elements marked with MDL classes upon page load. However in the case where you are creating DOM elements dynamically you need to register new elements using the upgradeElement function.

So loading the material.js script again will not execute it. But you can do some experiments with upgradeElements by applying it to the whole loaded markup or to particular elements.

查看更多
登录 后发表回答