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

技术求助:点击子Div内按钮时如何在父Div中加载指定页面

问题解决:点击动态加载按钮在父容器加载页面

点击xxx.php中动态插入到main.php的view按钮时,无法在index.php的#a容器中加载project_view.php,以下是问题分析和修复方案:

一、修复语法错误

xxx.php中的jQuery代码存在语法错误,调用load方法时缺少点号:
错误代码:

$('#a')load('project_view.php');

修复后:

$('#a').load('project_view.php');

二、解决动态元素事件绑定失效问题

xxx.php的内容是通过AJAX动态插入到页面的,$(document).ready()只会在页面初始加载时执行,此时动态生成的view按钮还不存在,导致事件绑定无效。需要使用事件委托,将事件绑定到已存在的父元素或document上:

修改xxx.php中的脚本:

$(document).on('click', '#view1, #view2, #view3', function(e) {
    // 阻止a标签默认跳转行为
    e.preventDefault();
    $('#a').load('project_view.php');
});

三、避免重复加载与重复绑定

main.php中setInterval每隔1秒重复加载xxx.php,会导致内容频繁替换、脚本重复执行,进而引发事件多次绑定。建议仅在页面加载时加载一次xxx.php:

修改main.php的脚本:

function loadXMLDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("b").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "xxx.php", true);
  xhttp.send();
}

// 仅在页面加载时执行一次
window.onload = loadXMLDoc;

若需定时更新内容,建议添加内容变化判断逻辑,避免无意义的重复请求。

四、完整修复后代码示例

xxx.php

<a href="#" id="view1">view proj1</a>
<a href="#" id="view2">view proj2</a>
<a href="#" id="view3">view proj3</a>

<script>
$(document).on('click', '#view1, #view2, #view3', function(e) {
    e.preventDefault();
    $('#a').load('project_view.php');
});
</script>

main.php

<div class="container-fluid">
    <div id="b"></div>
</div>
<script>
function loadXMLDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("b").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "xxx.php", true);
  xhttp.send();
}

window.onload = loadXMLDoc;
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 05:35:21