You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用jQuery无法更新动态加载HTML模板内元素ID对应内容怎么办

问题原因

你代码的核心问题是 jQuery的load()方法是异步执行的:

  • 你调用$("#page-banner-area").load(xxx)只是发起了一个加载模板的网络请求,代码不会等请求完成就会立刻执行后面修改#title、#keypoint-1等元素内容的逻辑
  • 此时模板还没加载完成,也没有被插入到当前页面的DOM树里,你的选择器找不到对应的元素,自然修改不会生效

修复方案

你只需要把DOM修改的逻辑放到load()方法的回调函数里即可,回调函数会在模板加载完成、且已经插入到页面后才触发,修改逻辑就能正常生效。
修复后的index.html相关代码如下:

<div id="page-banner-area"></div> 

<script>
$(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!');
  });
});
</script>

内容的提问来源于stack exchange,提问作者JamesReed68

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 17:39:03