简体   繁体   English

动态添加时Bootstrap切换无法正常显示

[英]Bootstrap toggle doesn't display well when added dynamically

I'm trying to add bootstrap toggle switch dynamically but it does not display well after adding it. 我正在尝试动态添加引导切换开关,但添加后显示不佳。 Thanks for your help! 谢谢你的帮助!

<input id="TheCheckBox" type="checkbox" data-off-text="Yes" data-on-text="No" checked="false" class="BSswitch">

<p> <a class="btn btn-lg btn-primary" href="#">Display another Toggle</a></p>
$('.btn').on('click', function () {
    $('p').after(
        '<input id="TheCheckBox" type="checkbox" data-off-text="Male" data-on-text="Female" checked="false" class="BSswitch">'
    );
});

This is the Jsfiddle: http://jsfiddle.net/icamilo95/8wars2ep/3/ 这是Jsfiddle: http : //jsfiddle.net/icamilo95/8wars2ep/3/

You need to call the bootstrapSwitch() again after adding and with a new ID, class or else it will alter the states of existing toggle as well. 您需要在添加后使用新的ID,类再次调用bootstrapSwitch() ,否则它将同时更改现有切换的状态。

$('.btn').on('click', function () {
    $('p').after(
        '<input id="newCheckBox" type="checkbox" data-off-text="Male" data-on-text="Female" checked="false" class="newBSswitch">'
    );
    $('.newBSswitch').bootstrapSwitch('state', true); // Add
});

JSfiddle JS小提琴

Add Bootstrap toggle js after your main js file 在您的主要js文件之后添加Bootstrap切换js

Then call bootstrapswitch statement in your js file 然后在您的js文件中调用bootstrapswitch语句

$('.your_toggle_class_name').bootstrapSwitch('state', true); 

I was facing the same issue using bootstrap-toggle. 我在使用bootstrap-toggle时遇到了同样的问题。 Then after debugging, I understood the behaviour and handled it. 然后,在调试之后,我了解了行为并进行了处理。

If the checkbox is not in the dom when page loads, then we need to initialize the toggler when the checkbox is available to the dom and also any listener methods. 如果页面加载时该复选框不在dom中,则当该复选框可用于dom以及所有侦听器方法时,我们需要初始化切换器。

if you are doing an ajax call then in the success method you can add the following in the end. 如果您正在执行ajax调用,则可以在成功方法中最后添加以下内容。

$("[data-toggle='toggle']").bootstrapToggle('destroy')                 
$("[data-toggle='toggle']").bootstrapToggle();

sometimes it may take time to add to the dom and your code gets run before checkbox getting added to the dom, you can wrap the above code in a javascript timer 有时可能需要花费一些时间才能添加到dom,并且在将复选框添加到dom之前运行您的代码,您可以将上述代码包装在javascript计时器中

     setTimeout( () => {
                    $("[data-toggle='toggle']").bootstrapToggle('destroy')                 
                    $("[data-toggle='toggle']").bootstrapToggle();
                    $(".checkbox").change(function() {
                      console.log("toggled");
                       });
                    }, 100 );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM