点击d3.js树节点加载外部stepper.html的jQuery load替代方案咨询
实现方案
你之前的代码未生效有两个核心原因:
- 代码是页面初始化时执行,没有绑定到节点的点击事件中
- 你的步进器代码使用了AngularJS指令,直接插入HTML不会触发指令编译,
ng-click等逻辑无法生效
前置准备
先在index.html中添加用于承载步进器的容器:
<div id="includedContent"></div>
方案1:原生Fetch实现(无需依赖jQuery)
修改你的click事件函数如下:
async function click(event, d) { // 此处保留你原来click函数里的其他原有逻辑 try { // 加载stepper.html内容 const response = await fetch('views/stepper.html'); if (!response.ok) throw new Error('步进器文件加载失败'); const htmlStr = await response.text(); const container = document.querySelector('#includedContent'); // 插入HTML内容 container.innerHTML = htmlStr; // 编译AngularJS指令,让ng-*相关逻辑生效 const scope = angular.element(container).scope(); angular.element(container).injector().invoke(function($compile) { $compile(container)(scope); scope.$apply(); }); } catch (error) { console.error(error); } }
方案2:jQuery实现(jQuery.load并未废弃,调整使用方式即可)
修改你的click事件函数如下:
function click(event, d) { // 此处保留你原来click函数里的其他原有逻辑 $('#includedContent').load('views/stepper.html', function() { // 加载完成后编译AngularJS指令 const container = document.querySelector('#includedContent'); const scope = angular.element(container).scope(); angular.element(container).injector().invoke(function($compile) { $compile(container)(scope); scope.$apply(); }); }); }
注意事项
- 路径校验:确认
views/stepper.html的相对路径是相对于index.html的,而非相对于app.js,路径错误会返回404 - 本地调试:不要直接用
file://协议打开index.html,会触发跨域限制导致加载失败,建议用本地服务(如VSCode的Live Server插件)启动页面 - 性能优化:如果不需要每次点击都刷新步进器内容,可以把第一次加载的HTML缓存起来,后续点击直接复用,避免重复请求
内容的提问来源于stack exchange,提问作者MaxyCar
相关产品推荐
相关产品推荐

