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

JavaScript如何实现问卷应用删除指定选项、问题元素功能

问卷选项/问题删除功能实现方案

你当前已经用事件委托处理按钮点击,这个写法非常适合扩展删除功能,核心逻辑和你已有的新增逻辑一致,通过DOM树定位到要删除的目标元素后调用原生remove()方法即可,逻辑可以直接复用到问题删除场景。

选项删除代码补全

在你留空的removeButton判断分支中,直接写入以下代码即可实现点击删除对应选项:

// 定位当前按钮所属的选项元素
const targetOption = ev.target.closest(".optionName");
// 校验元素存在后执行删除,避免异常
if (targetOption) {
  targetOption.remove();
}

这里用closest()方法而不是链式调用parentElement,是因为closest()会自动向上查找匹配对应选择器的最近祖先节点,后续如果你调整选项内部的DOM结构(比如给按钮加图标、套一层装饰容器),这段代码依然能正常工作,不需要跟着调整层级。

复用逻辑实现问题删除

后续要做问题删除功能,完全可以套用相同的逻辑,只需要两步:

  • 修改newQuestion函数的模板字符串,在问题容器内新增删除问题的按钮:
<button class="removeQuestionButton" type="button">Remove Question</button>
  • 在点击事件的判断分支中新增对应逻辑,和删选项的逻辑几乎一致,仅修改要匹配的祖先选择器即可:
else if (ev.target.classList.contains("removeQuestionButton")) {
  const targetQuestion = ev.target.closest(".question");
  if (targetQuestion) {
    targetQuestion.remove();
  }
}

优化建议

  • 你当前用ev.target.className === "类名"的写法做判断,后续如果给元素加多个样式类会匹配失效,建议统一换成ev.target.classList.contains("类名")的写法,容错性更高。
  • 可以按需增加删除确认逻辑,比如执行删除前调用if(!confirm("确定要删除该内容吗?")) return,避免用户误点导致内容丢失。

完整修改后JS代码

const questionnaire = document.getElementById('questionaire');
newQuestion();

function newQuestion() {
    questionnaire.insertAdjacentHTML('beforeend',
        `<div class="question"> <div contenteditable="true">Your Question</div>
    <ul> </ul>
    <button class="addButton" type="button">Add Option</button>
    <button class="removeQuestionButton" type="button">Remove Question</button>
   </div>`);
    newOption(questionnaire.querySelector("div.question:last-child ul"));
}

function newOption(q) {
    q.insertAdjacentHTML('beforeend',
        `<li class="optionName">
      <span contenteditable="true">Option</span>
      <input type="checkbox"> 
      <button class="removeButton" type="button">Remove Option</button>
     </li>`);
}

questionnaire.onclick = ev => {
    if (ev.target.tagName === "BUTTON") {
        if (ev.target.classList.contains("addButton")) {
            newOption(ev.target.closest(".question").querySelector('ul'))
        }
        else if (ev.target.classList.contains("removeButton")) {
            const targetOption = ev.target.closest(".optionName");
            if (targetOption) targetOption.remove();
        }
        else if (ev.target.classList.contains("removeQuestionButton")) {
            const targetQuestion = ev.target.closest(".question");
            if (targetQuestion) targetQuestion.remove();
        }
    }
}

document.getElementById("addQuButton").onclick = newQuestion

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 03:00:58