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

点击提交按钮后如何为每个选中项生成独立<div>元素?

实现每个选中项独立在单独
的解决方案

当然没问题!你要的「每个选中项各自独立位于一个

」的需求完全可以实现,核心思路就是每次点击「Add Item」按钮时,为当前选中的条目单独创建一个新的
元素,再把它插入到指定的容器中,而不是把所有文本都塞进同一个
里。

下面是具体的实现步骤和代码示例,我基于你提供的HTML片段补全了完整逻辑:

1. 先完善HTML结构

首先我们需要一个专门的容器来存放这些独立的选中项,同时补全你给出的可选项结构(假设你有多个item):

<div class="select-group">
  <!-- 第一项 -->
  <p class="item-selection">item 1</p>
  <button type="button" class="btn btn-default check">Add Item</button>

  <!-- 第二项 -->
  <p class="item-selection">item 2</p>
  <button type="button" class="btn btn-default check">Add Item</button>

  <!-- 第三项 -->
  <p class="item-selection">item 3</p>
  <button type="button" class="btn btn-default check">Add Item</button>
</div>

<!-- 用来存放每个独立选中项的容器 -->
<div id="selected-items-container"></div>

2. 编写JavaScript点击逻辑

接下来给每个「Add Item」按钮绑定点击事件,每次点击时生成独立的

并添加到容器:

// 获取所有的添加按钮
const addButtons = document.querySelectorAll('.btn.check');
// 获取存放选中项的容器
const selectedContainer = document.getElementById('selected-items-container');

// 遍历每个按钮,绑定点击事件
addButtons.forEach(button => {
  button.addEventListener('click', function() {
    // 获取当前按钮对应的item文本(找到它前面的.item-selection元素)
    const itemText = this.previousElementSibling.textContent.trim();
    
    // 创建一个新的div元素
    const newItemDiv = document.createElement('div');
    // 给这个div加个类名,方便后续样式控制
    newItemDiv.classList.add('selected-item');
    // 设置div的内容为选中的item文本
    newItemDiv.textContent = itemText;
    
    // 把新创建的div添加到容器里
    selectedContainer.appendChild(newItemDiv);

    // 👉 可选优化:如果不想重复添加同一个item,可以加个判断
    // const existingItems = Array.from(selectedContainer.children).map(el => el.textContent);
    // if (!existingItems.includes(itemText)) {
    //   selectedContainer.appendChild(newItemDiv);
    // }
  });
});

3. 可选:添加样式让选中项更美观

你可以给独立的选中项div加一些基础样式,让它看起来更清晰:

.selected-item {
  padding: 8px 14px;
  background-color: #f5f5f5;
  border-radius: 4px;
  margin: 6px 0;
  border: 1px solid #eee;
}

这样操作后,每次点击「Add Item」按钮,对应的条目就会被包裹在一个独立的

中,添加到选中项容器里啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 04:02:42