我需要动态创建一个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 + '"/>'我得到了以下结果:

下面的是静态添加的,并且显示正确。上面的一个是动态生成的,但它只显示为一个复选框。所以我的问题是,我该如何解决这个问题?
发布于 2020-05-03 07:42:05
简单地使用class="js-switch"向DOM添加新输入并不会创建Switchery-style开关。
必须为每个输入创建一个JavaScript交换机对象。
此函数将DOM中的所有非Switchery输入转换为Switchery风格的开关:
// 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>
参考文献:
发布于 2020-05-03 09:48:03
在看了文档之后,我确实发现了一些有用的东西。
我首先需要将代码添加到将包含开关的实际元素中。
document.getElementById("mainPanel").innerHTML = html;只有在添加了代码之后,我才能使用这两行代码启用切换,这两行代码是从文档中复制和粘贴的
// This is required to enable Switchery.
var elem = document.querySelector('.js-switch');
var init = new Switchery(elem); 希望这对其他人有帮助!
https://stackoverflow.com/questions/61567678
复制相似问题