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

如何实现点击按钮加载多个自定义结构的div元素

解决方案

核心调整点

  1. 将你提供的自定义CSS样式加入页面的<head>标签中,保证渲染出来的卡片样式符合预期
  2. 替换加载逻辑中append的内容,把原来的简单div替换为你需要的自定义卡片结构,同时动态填充items数组内的文本内容

完整可运行代码

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>加载更多内容</title>
    <script
  src="https://code.jquery.com/jquery-3.4.1.min.js"
  integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
  crossorigin="anonymous"></script>
  <style>
    .main-box {
        background-color: #ffffff;
        height: 130px;
        display: flex;
        width: 798px;
        border-right: solid;
        border-left: solid;
        border-bottom: solid;
        border-color: #E6E6E6;
        margin-bottom: 10px;
    }

    .text-in-main-box{
        font-weight: bold;
        font-family: sans-serif;
        width: 60%;
        padding: 7%;
        display: flex;
        align-items: center;
    }

    .container-for-button-in-main-box{
        width: 40%;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
    }
    .button-in-main-box{
        display:inline-block;
        padding:0.8em 1.2em;
        margin:0 0.3em 0.3em 0;
        box-sizing: border-box;
        text-decoration:none;
        font-family: sans-serif;
        font-weight:bold;
        color:#ffffff;
        background-color:#34E034;
        text-align:center;
        transition: all 0.2s;
        font-size: 14px;
        border-radius: 4em;
        cursor: pointer;
    }
  </style>
</head>
<body>
<h1>加载更多内容</h1>
<div id="content"></div>
<button id="lmbutton" onclick="loadmore()">加载更多</button>
<script>
    // 可替换为你自己的任务标题列表
    var items = ["使用Python输出“Hello World”", "Python变量定义练习", "Python循环语句实操", "Python函数封装训练", "Python文件读写练习", "Python异常处理练习", "Python爬虫入门", "Python数据分析基础", "Python可视化实操", "Python项目部署"]
    var currentindex = 0
    function loadmore(){
        var maxresult = 2
        for(var i = 0; i < maxresult; i++){
            if(currentindex >= items.length){
                $("#lmbutton").hide()
                return
            }
            // 替换为自定义卡片结构,动态插入标题
            $("#content").append(`<div class="main-box">
                <div class="text-in-main-box">${items[i+currentindex]}</div>
                <div class="container-for-button-in-main-box"><span class="button-in-main-box">完成任务</span></div>
            </div>`)
        }
        currentindex += maxresult
    }
    loadmore()
</script>
</body>
</html>

补充说明

  • 原有加载逻辑完全保留:首次加载2条,每次点击按钮加载2条,全部内容加载完成后按钮自动隐藏
  • 我优化了CSS部分属性:将原来兼容性不好的vertical-align: middle替换为flex布局适配的align-items: center,同时给卡片加了底部边距避免粘连,还添加了按钮鼠标悬浮手型效果,你可以根据需求调整
  • 如果需要每个卡片的按钮文本也不一样,可以把items改为对象数组,分别存储标题和按钮文本后动态填充即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 13:24:03