Usando JS y AJAX, estoy cargando un archivo de plantilla en mi página Index.html. Una vez que se carga la plantilla, quiero aplicar cambios al DOM.
¿Qué estoy haciendo mal?
Tengo 2 páginas html.
índice.html
<div id="page-banner-area"></div> <script> $(function(){ $("#page-banner-area").load("assets/static_html/page-banner-area.html"); $("#title").text('Join a Community Group in your area.'); $("#keypoint-1").text('We are against mandatory vaccines & passports.'); $("#keypoint-2").text('We do not stand for corruption & censorship.'); $("#keypoint-3").text('We believe in freedom!'); }); </script>pagina-banner-area.html
<div class="p-2 flex-grow-1"> <h3><span id="title"></span></h3> <span id="keypoint-1"></span><br /> <span id="keypoint-2"></span><br /> <span id="keypoint-3"></span> </div>El problema es que el método load() es asíncrono, debe realizar los cambios dentro de un método de devolución de llamada para que se apliquen correctamente. Consulte los documentos de JQuery para obtener más información https://api.jquery.com/load/
En cuanto a una solución, deberías estar haciendo esto en su lugar:
$(function(){ $("#page-banner-area").load("assets/static_html/page-banner-area.html", function() { $("#title").text('Join a Community Group in your area.'); $("#keypoint-1").text('We are against mandatory vaccines & passports.'); $("#keypoint-2").text('We do not stand for corruption & censorship.'); $("#keypoint-3").text('We believe in freedom!'); }); });¡Creo que esto puede resolver tu problema!
<div id="page-banner-area"></div> <script> $(() => { $("#page-banner-area") .load("assets/static_html/page-banner-area.html", () => { $("#title").text('Join a Community Group in your area.'); $("#keypoint-1").text('We are against mandatory vaccines & passports.'); $("#keypoint-2").text('We do not stand for corruption & censorship.'); $("#keypoint-3").text('We believe in freedom!'); }); }); </script>