如何在onload()函数中编写HTML代码实现子菜单加载后默认加载首个子项
问题修正方案
问题根源
onload事件仅支持<body>、<img>、<script>、<iframe>等少数资源加载类元素,<a>标签本身不触发onload事件,所以你写在菜单项a标签上的onload="loadfirst()"永远不会执行。- 你需要的触发时机是
fetch请求完成、submenu的HTML内容已经插入DOM之后,直接在load_menu的回调链路里加触发逻辑是最稳妥的实现方式。
具体修改步骤
1. 调整JS代码
<script> function load_menu(htmname) { fetch(htmname /*, options */) .then((response) => response.text()) .then((html) => { const submenuEl = document.getElementById("submenu"); submenuEl.innerHTML = html; // submenu内容插入完成后直接调用加载第一个子项 loadfirst(); }) .catch((error) => { console.warn(error); }); } function load_data(htmfile) { fetch(htmfile /*, options */) .then((response) => response.text()) .then((html) => { document.getElementById("detail").innerHTML = html; }) .catch((error) => { console.warn(error); }); } function loadfirst() { // 写法1:固定写死第一个子项路径,适合路径固定的场景 load_data("./iNat_files/PID297.html"); // 写法2:自动取submenu里第一个a标签的目标路径,不用每次改子菜单都改JS,更灵活 // const firstSubmenuA = document.querySelector("#submenu li:first-child a"); // if (firstSubmenuA) firstSubmenuA.click(); // 直接触发点击事件,复用已有的onclick逻辑 } </script>
2. 调整HTML代码
删除菜单项a标签上无效的onload属性即可,子菜单项不需要做任何修改:
/* 点击触发的菜单项 */ <li><a href="#submenu" onclick="load_menu('./iNat_files/P_menu.html')">Plants</a></li> /* 待触发的首个子菜单项 */ <li><a href="#detail" onclick="load_data('./iNat_files/PID297.html')"># 297: = Centaurea crocodylium</a></li>
内容的提问来源于stack exchange,提问作者Shmuel
相关产品推荐
相关产品推荐

