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

JS待办事项:点击Update按钮更新列表项值的实现问题

解决待办事项Edit/Update功能的更新问题

修改后的JavaScript代码

const itemName = document.querySelector('.item_name');
const editBTN = document.querySelector('.item_edit');

editBTN.addEventListener('click', () => {
  // 判断当前按钮状态是Edit还是Update
  if (editBTN.innerText === 'Edit') {
    // 进入编辑模式:替换span为输入框
    const currentText = itemName.textContent;
    itemName.innerHTML = '';
    
    const newItemInput = document.createElement('input');
    newItemInput.type = 'text';
    newItemInput.className = 'newItemInput';
    newItemInput.value = currentText; // 填充原有文本
    itemName.appendChild(newItemInput);
    newItemInput.focus();
    
    editBTN.innerText = 'Update';
  } else {
    // 进入更新模式:替换输入框为新文本
    const inputElement = itemName.querySelector('.newItemInput');
    const updatedText = inputElement.value.trim();
    
    if (updatedText) { // 确保输入不为空
      itemName.innerHTML = `<span class="item_name">${updatedText}</span>`;
    }
    
    editBTN.innerText = 'Edit';
  }
});

关键修改说明

  • 避免重复绑定事件:移除了原代码中重复绑定点击事件的逻辑,改用单次事件绑定+按钮文本判断状态,防止多次点击后触发冗余逻辑。
  • 保留原有文本:进入编辑模式时自动填充原列表项的文本,提升使用体验。
  • 完成更新替换:点击Update按钮时,获取输入框内容并替换原列表项的文本,同时将按钮恢复为初始的Edit状态。
  • 空值校验:添加输入内容非空判断,避免空内容覆盖原列表项。

原HTML代码(无需修改)

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" integrity="sha512-iecdLmaskl7CVkqkXNQ/ZH/XLlvWZOJyj7Yy7tcenmpD1ypASozpmT/E0iPtmFIB46ZmdtAc9eNBvH0H/ZpiBw==" crossorigin="anonymous" referrerpolicy="no-referrer" />

<section class="list">
  <header class="header">Shopping List</header>
  <ul class="items">
    <li class="item_row">
      <div class="item">
        <input type="checkbox" id="item_name_check" value="1" />
        <label for="item_name_check"><span class="item_name">Egg</span></label>
        <div class="button_container">
          <button class="item_edit">Edit</button>
          <button class="item_delete">
            <i class="fas fa-trash-can"></i>
          </button>
        </div>
      </div>
    </li>
  </ul>
  <form class="new_form">
    <footer class="footer">
      <input type="text" class="footer_input" />
      <button type="submit" class="footer_button">
        <i class="fas fa-plus"></i>
      </button>
    </footer>
  </form>
</section>

内容的提问来源于stack exchange,提问作者Chocolate covered Strawberry

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 02:12:25