javascript - 将动态创建的复选框输入转换为 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 + '"/>'
我得到这些结果:
下面的一个是静态添加的,它显示正确。上面的一个是动态生成的,但它只显示为一个复选框。所以我的问题是,我该如何解决这个问题?
解决方案
简单地将新输入添加到 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>
参考:
推荐阅读
- sparql - 可以遵循类型链来测试它的结束位置吗?
- java - 检查图像 URL 是否指向实际图像。URL中的空格导致问题
- sql-server - Visual Studio 2019 数据库架构比较忽略外键名称
- flutter - 用 Stack 定位 Carosel_slider,溢出屏幕像素
- python - pytorch 元素相交
- validation - 针对目录中多个 CA 的 Openssl 证书验证
- javascript - 在 Vue 中使用 Pusher 进行 Chrome 扩展
- sql-server - 按名称从另一个容器连接到 SQL Server 容器
- javascript - 嘿,我想用画布和js制作这个小程序,它可以检测圆圈之间的碰撞
- haskell - Haskell Gnuplot 没有响应标题功能