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

如何在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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 09:30:05