使用JS和AJAX,我将在Index.html页面上加载一个模板文件。加载模板后,我想将更改应用到DOM。
我做错什么了?
我有两个html页面。
index.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>page-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>发布于 2021-09-23 02:22:50
问题是,load()方法是异步的,您需要在回调方法中执行更改,以便正确应用它们。有关更多信息,请参见JQuery文档https://api.jquery.com/load/
至于解决方案,您应该这样做:
$(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!');
});
});发布于 2021-09-23 02:23:40
我认为这能解决你的问题!
<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>
https://stackoverflow.com/questions/69293256
复制相似问题