简体   繁体   中英

Bootstrap carousel is not working if set it with JS

Bootstrap carousel does not work in example below. It works when I copy it to .content

 <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> <script> function Type_Button() { $("div#content").html('<div id="Doodle" class="carousel slide" data-ride="carousel" data-interval="500"><div class="carousel-inner"><div class="item active" style="padding: 0;"><img src="https://www.google.com/logos/doodles/2020/stay-and-play-at-home-with-popular-past-google-doodles-loteria-2019-6753651837108772.2-2xa.gif"></div><div class="item" style="padding: 0;"><img src="https://www.google.com/logos/doodles/2020/stay-and-play-at-home-with-popular-past-google-doodles-halloween-2016-6753651837108773-2xa.gif"></div></div></div>'); } window.onload = Type_Button; </script> </head> <body> <div id="content"></div> </body>

You need to call the carousel method manually as you're trying to inject the html code after body onload.

Call carousel manually (at the end of Type_Button() function) with:

$('.carousel').carousel()

You can try a bunch of options inside it - check -> https://getbootstrap.com/docs/4.3/components/carousel/#options

 <html> <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> <script> function Type_Button() { $("div#content").html('<div id="Doodle" class="carousel slide" data-ride="carousel" data-interval="500"><div class="carousel-inner"><div class="item active" style="padding: 0;"><img src="https://www.google.com/logos/doodles/2020/stay-and-play-at-home-with-popular-past-google-doodles-loteria-2019-6753651837108772.2-2xa.gif"></div><div class="item" style="padding: 0;"><img src="https://www.google.com/logos/doodles/2020/stay-and-play-at-home-with-popular-past-google-doodles-halloween-2016-6753651837108773-2xa.gif"></div></div></div>'); $('.carousel').carousel(); } window.onload = Type_Button; </script> </head> <body> <div id="content"> </div> </body> </html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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