首页 > 解决方案 > 将动态创建的复选框输入转换为 Switchery 样式的开关

问题描述

我需要动态创建一个Switchery开关。

我正在创建这样的非动态开关:

<div class="item form-group">
   <label class="control-label col-md-3 col-sm-3 col-xs-12">Admin User</label>
   <div class="col-md-6 col-sm-6 col-xs-12">
      <input type="checkbox" class="js-switch" id= "canModify"/>
   </div>
</div> 

这很好用。

但是,当我像这样通过 JavaScript 创建相同的结构时:

  html = '<input type="checkbox" class="js-switch" id= "' + elementID +  '"/>'

我得到这些结果:

不加载 js-switch 的外观

下面的一个是静态添加的,它显示正确。上面的一个是动态生成的,但它只显示为一个复选框。所以我的问题是,我该如何解决这个问题?

标签: javascripthtmltwitter-bootstrapswitchery

解决方案


简单地将新输入添加到 DOMclass="js-switch"不会创建Switchery样式的开关。

必须为每个输入创建一个 JavaScript Switchery 对象。

此函数会将 DOM 中的所有非切换输入转换为切换式开关:

// convert all inputs with class="js-switch" to Switchery
function convertToSwitchery() {

  // get all "js-switch" class inputs in the DOM
  const jsSwitchInputs = document.querySelectorAll('.js-switch');

  jsSwitchInputs.forEach(input => {
    // ignore if input is already switchery
    if (input.dataset.switchery) {
      return;
    }
    // create new Switchery object
    new Switchery(input);
  });
}

一个工作示例:

// convert all inputs with class="js-switch" to Switchery-style
function convertToSwitchery() {
  const jsSwitchInputs = document.querySelectorAll('.js-switch');
  jsSwitchInputs.forEach(input => {
    // ignore if input is already switchery
    if (input.dataset.switchery) {
      return;
    }
    new Switchery(input);
  });
}



// code for demo only:
const divResult = document.getElementById('result');
let iButton = 0;

// add a new "js-switch" input
function addInput() {
  const br = document.createElement('br');
  divResult.appendChild(br);
  const label = document.createElement('label');
  label.for = `input${++iButton}`;
  label.className = 'mr-4';
  label.innerHTML = `Dynamic "js-switch" ${iButton} `;
  divResult.appendChild(label);
  const input = document.createElement('input');
  input.type = 'checkbox';
  input.className = 'js-switch';
  input.id = `input${iButton}`;
  divResult.appendChild(input);
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/switchery-latest@0.8.2/switchery.css" rel="stylesheet" />

<div class="p-4">
  <h4>Convert Checkbox Inputs to Switchery Style</h4>
  <button class="btn btn-primary btn-sm" onclick="addInput();">
    Add ".js-switch"</button>
  <button class="btn btn-primary btn-sm"
    onclick="convertToSwitchery();">
    Convert All to Switchery</button>
    
  <div class="mt-4" id="result">
    <label for="static-input">Static "js-switch"</label>
    <input type="checkbox" class="js-switch" checked />
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/switchery-latest@0.8.2/dist/switchery.min.js"></script>

参考:


推荐阅读