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

页面加载时隐藏div,点击按钮逐个显示多个div的实现疑问

实现点击按钮逐个显示隐藏的Div

修正要点与完整代码

首先修正函数名大小写不一致的问题(按钮onclick绑定的是AddItem(),原函数定义为Additem()),再通过计数器跟踪显示进度,实现逐个显示:

<div id="realProp1">
    <input name="FirstName[0]" class="form-control" />
</div>

<div id="realProp2">
    <input name="FirstName[1]" class="form-control" />
</div>

<div id="realProp3">
    <input name="FirstName[2]" class="form-control" />
</div>

<button type="button" onclick="AddItem()" class="btn btn-primary">Add Item</button>

<script>
// 初始化计数器,记录下一个要显示的Div序号
let currentIndex = 1;
// 页面加载时隐藏所有目标Div
window.onload = function () {
    for (let i = 1; i <= 3; i++) {
        document.getElementById(`realProp${i}`).style.display = 'none';
    }
};

function AddItem() {
    // 获取当前要显示的Div
    const targetDiv = document.getElementById(`realProp${currentIndex}`);
    if (targetDiv) {
        targetDiv.style.display = '';
        currentIndex++;
        // 所有Div显示完后禁用按钮
        if (currentIndex > 3) {
            document.querySelector('.btn-primary').disabled = true;
        }
    }
}
</script>

代码说明

  • 初始化隐藏:通过循环批量隐藏realProp1到realProp3,比逐个编写更简洁。
  • 计数器逻辑:currentIndex从1开始,每次点击按钮时找到对应ID的Div并显示,然后计数器递增。
  • 边界处理:当计数器超过3时,禁用按钮,避免无效点击。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 13:30:44