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

jQuery动态添加内容位置错误问题求助

解决内容插入位置的问题

问题出在你使用的append()方法上——这个方法会把新内容追加到目标元素的最后子节点位置,所以新的.e块会被放到.b容器的最底部,也就是.g按钮块的后面。要把内容插到.g的上方,我们只需要调整DOM插入的方法即可。

修改方案

你可以通过以下两种方式实现需求:

方法一:直接定位.g容器并在前方插入

把jQuery代码里的append替换成before逻辑,先找到当前按钮所在的.g容器,然后在它前面插入新内容:

$(document.body).on('click', 'button.js-add-Section', function () {
    // 建议给新增section加递增编号,避免标题重复
    const sectionCount = $(this).closest('.b').find('.e').length + 1;
    var content = `
        <div class="e"> 
            <ul> 
                for (int j = 1; j <= numOfCheckboxes; j++) { 
                    <li> 
                        <input type="checkbox" id="user-@j-${sectionCount}"> 
                        <label for="user-@j-${sectionCount}"><i class="icon-tick" disabled></i></label> 
                    </li> 
                } 
            </ul> 
            <div class="f"> 
                <small class="_availability"> 
                    <span class="title"> Section ${sectionCount} </span> 
                </small> 
                <button type="button" class="mdl-button btn-show js-show-supplier"> 
                    <span class="show">Show <i class="icon-show"></i></span> 
                </button> 
            </div> 
        </div>
    `;
    // 关键修改:找到当前按钮所在的.g容器,在它前面插入内容
    $(this).closest('.g').before(content);
});

方法二:通过父容器.b定位.g插入

如果你更倾向于从.b容器出发,也可以这样写:

$(document.body).on('click', 'button.js-add-Section', function () {
    const sectionCount = $(this).closest('.b').find('.e').length + 1;
    var content = `<!-- 你的内容块,记得更新section编号和checkbox的id -->`;
    const $parentB = $(this).closest('.b');
    // 找到.b里的.g元素,在它前面插入新内容
    $parentB.find('.g').before(content);
});

额外提示

我顺便给代码加了section编号递增的逻辑,避免所有新增块的标题和checkbox id重复,如果你不需要可以直接删掉相关部分~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:21:14