使用Javascript以编程方式创建MDL开关

时间:2018-07-15 00:14:21

标签: javascript html material-design material-design-lite

我有一个无法解决的有关MDL的问题。

仅使用HTML即可完美运行:

<label class="mdl-switch mdl-js-switch mdl-js-ripple-effect" for="switch-1">
    <input onchange="handleDisableEnabled(this)" type="checkbox" id="switch-1"
           class="mdl-switch__input" checked>
    </label>
<span class="mdl-switch__label"></span>

但是当我做这样的事情时:

<span id='foo'></span>

<script>
document.getElementById("foo").innerHTML = '<label class="mdl-switch mdl-js-switch mdl-js-ripple-effect" for="switch-1">
<input onchange="handleDisableEnabled(this)" type="checkbox" id="switch-1" class="mdl-switch__input" checked></label>
<span class="mdl-switch__label"></span>';
</script>

它仅输出不带格式的普通复选框。有什么办法可以通过Javascript创建开关吗?谢谢!

1 个答案:

答案 0 :(得分:0)

您需要调用componentHandler.upgradeElement(elementName)来实例化动态创建的MDL组件。有关更多详细信息,请参见How the Component Handler works。例如:

let fragment = document.createDocumentFragment();
let label = document.createElement('label');
let input = document.createElement('input');
let span = document.createElement('span');
span.textContent = 'Switch';

Object.assign(label, {className: 'mdl-switch mdl-js-switch mdl-js-ripple-effect'});
label.setAttribute('for', 'switch-1');
Object.assign(input, {type: 'checkbox', className: 'mdl-switch__input', id: 'switch-1'});
Object.assign(span, {className: 'mdl-switch__label'});

fragment.appendChild(label);
label.appendChild(input);
label.appendChild(span);

componentHandler.upgradeElement(label);
document.querySelector('#container').appendChild(fragment);
<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Material Design Lite Switch</title>
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
    <link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.indigo-pink.min.css">
  </head>

  <body>

    <div id="container"></div>

    <script src="https://code.getmdl.io/1.3.0/material.min.js"></script>
    
  </body>

</html>