You need to enable JavaScript to run this app. 如何阻止空输入时添加按钮提交 及优化已废弃的回车提交写法
优惠活动
大模型
产品
解决方案
定价
更多

如何阻止空输入时添加按钮提交 及优化已废弃的回车提交写法

问题排查

你原来的代码存在几个核心错误导致功能不符合预期:

  • 校验逻辑执行顺序错误:add函数中先把输入值插入数组、执行渲染后才做非空判断,空值已经被添加到列表中才做校验完全无效
  • 判断运算符使用错误:if(groceryInput.length = 0)是赋值语句,不是相等判断,应该用===
  • 回车事件使用了废弃属性:KeyboardEvent.which已经被标准废弃,同时displayGroceries里多余的keyCode判断逻辑完全无作用,属于冗余代码
  • 变量未声明:groceryInput没有加let/const声明,会隐式变为全局变量,可能引发其他问题
优化实现

1. 空值校验实现

优先对输入值做去空格处理,空值直接终止函数执行,还可以加输入框实时监听控制按钮禁用状态,提升使用体验。

2. 回车提交实现

推荐用表单原生能力实现:将输入框和按钮包裹在<form>标签内,利用表单自带的回车提交功能,无需额外写键盘监听逻辑,符合标准规范。如果不想改动HTML结构,也可以将键盘事件的判断逻辑替换为key === 'Enter',替代废弃的which属性。

完整修正代码

HTML部分

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Grocery List</title>
</head>
<body>
<div class="container">
    <h1>Grocery List</h1>
    <!-- 用form标签包裹实现原生回车提交 -->
    <form id="grocery-form">
        <input id="add-input" placeholder="Add Groceries" autocomplete="off">
        <button id="add-button" type="submit" disabled>Add</button>
    </form>
    <div>
        <ul id="grocery-ul"></ul>
    </div>
</div>
<script src="main.js"></script>
</body>
</html>

JS部分

const groceryForm = document.getElementById('grocery-form');
const addInput = document.getElementById('add-input');
const addButton = document.getElementById('add-button');
const groceryUl = document.getElementById('grocery-ul');
let groceryList = [];

// 表单提交事件,同时覆盖按钮点击和回车提交
groceryForm.addEventListener('submit', (e) => {
    // 阻止表单默认跳转行为
    e.preventDefault();
    add();
})

// 实时监听输入,控制按钮禁用状态
addInput.addEventListener('input', () => {
    addButton.disabled = addInput.value.trim().length === 0;
})

function add() {
    const groceryInput = addInput.value.trim();
    // 空值直接返回,不执行后续逻辑
    if(groceryInput.length === 0) return;
    
    groceryList.push(groceryInput);
    addInput.value = '';
    addButton.disabled = true;
    displayGroceries();
}

function remove(event) {
    const position = Number(event.currentTarget.id);
    groceryList.splice(position, 1);
    displayGroceries();
}

function displayGroceries() {
    groceryUl.innerHTML = '';
    for (let i = 0; i < groceryList.length; i++) {
        const groceryLi = document.createElement('li');
        groceryLi.innerText = groceryList[i];
        const removeButton = document.createElement('button');
        removeButton.innerText = "Remove";
        removeButton.addEventListener('click', remove);
        removeButton.id = i;
        groceryLi.appendChild(removeButton);
        groceryUl.appendChild(groceryLi);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 20:45:02