点击发送按钮后清除number输入框内容的实现方法
如何在发送完成后清除数字输入框内容
根据你的代码场景,分两种情况处理:
1. 如果liveSend是同步执行的函数
直接在调用liveSend之后,将输入框的value设为空字符串即可:
修改后的sendBid函数:
function sendBid() { const inputBox = document.getElementById('inputbox'); const bidValue = parseInt(inputBox.value); liveSend(bidValue); // 发送完成后清空输入框 inputBox.value = ''; }
如果习惯直接使用id全局变量(浏览器默认支持),也可以简化成:
function sendBid() { liveSend(parseInt(inputbox.value)); inputbox.value = ''; }
2. 如果liveSend是异步函数(比如发送网络请求)
异步函数不会立即执行完成,需要等它的异步操作结束后再清空输入框,具体写法看liveSend的实现方式:
方式A:liveSend返回Promise
用.then()处理成功回调:
function sendBid() { const inputBox = document.getElementById('inputbox'); const bidValue = parseInt(inputBox.value); liveSend(bidValue) .then(() => { // 发送成功后清空 inputBox.value = ''; }) .catch(err => { // 可选:处理发送失败的情况 console.error('发送失败:', err); }); }
或者用async/await语法,代码更简洁:
async function sendBid() { const inputBox = document.getElementById('inputbox'); const bidValue = parseInt(inputBox.value); try { await liveSend(bidValue); inputBox.value = ''; } catch (err) { console.error('发送失败:', err); } }
方式B:liveSend使用回调函数
如果liveSend支持传入回调函数表示完成,就在回调里清空:
function sendBid() { const inputBox = document.getElementById('inputbox'); const bidValue = parseInt(inputBox.value); // 假设liveSend的第二个参数是完成回调 liveSend(bidValue, function() { inputBox.value = ''; }); }
内容的提问来源于stack exchange,提问作者Papayapap
相关产品推荐
相关产品推荐

