如何仅使用Javascript动态添加新Bootstrap开关
就像这样:
<div class="toggle btn btn-primary" data-toggle="toggle" role="button" style="width: 61.0781px; height: 38px;">
<input type="checkbox" checked="" data-toggle="toggle" data-onstyle="primary">
<div class="toggle-group">
<label class="btn btn-primary toggle-on">
On
</label>
<label class="btn btn-light toggle-off">
Off
</label>
<span class="toggle-handle btn btn-light">
</span>
</div>
</div>
本站text
按钮可以这样添加
<script>
function addButton() {
var element = document.createElement("input");
element.type = "button";
element.value = "View Info";
element.name = "getInfo";
element.className = "btn btn-info btn-lg";
}
</script>
function addButton() {
var element = document.createElement("input");
element.type = "button";
element.value = "View Info";
element.name = "getInfo";
element.className = "btn btn-info btn-lg";
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">
<link href="https://cdn.jsdelivr.net/gh/gitbrent/bootstrap4-toggle@3.6.1/css/bootstrap4-toggle.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-Fy6S3B9q64WdZWQUiU+q4/2Lc9npb8tCaSX9FK7E8HnRr0Jz8D6OP9dO5Vg3Q9ct" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/gh/gitbrent/bootstrap4-toggle@3.6.1/js/bootstrap4-toggle.min.js"></script>
<div class="toggle btn btn-primary" data-toggle="toggle" role="button" style="width: 61.0781px; height: 38px;">
<input type="checkbox" checked="" data-toggle="toggle" data-onstyle="primary">
<div class="toggle-group">
<label class="btn btn-primary toggle-on">
On
</label>
<label class="btn btn-light toggle-off">
Off
</label>
<span class="toggle-handle btn btn-light">
</span>
</div>
</div>
2条答案
按热度按时间vsnjm48y1#
您需要在HTML中有一个父元素,在该元素下添加这个新创建的开关。
假设你的HTML中有一个
div#switch-host
。然后你将实现一个JS函数,它将把你的开关添加到这个div中,如下所示:
然后将此函数调用为
jrcvhitl2#
我想这就是你想要的。我使用了一些模板,因为我不喜欢代码中的所有内容。然后我用jQuery修改了值,因为这是一个jQuery插件。
参考:https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template