发布于2026-07-18 阅读(0)
扫一扫,手机访问
document.createElement 来动态创建输入框,同时给每个字段设置一个唯一标识(通常用 name 属性或 data-index),方便后续遍历。这里有个关键点:不要每次提交时再去DOM里查询一遍,而是维护一个实时同步的数组,集中管理所有输入值。
const container = document.getElementById('field-container');
const addBtn = document.getElementById('add-btn');
const submitBtn = document.getElementById('submit-btn');
const words = []; // 存储所有文本框当前值(建议用对象数组增强可维护性)
let fieldIndex = 0;
addBtn.addEventListener('click', () => {
const input = document.createElement('input');
input.type = 'text';
input.className = 'dynamic-field';
input.placeholder = `请输入第 ${++fieldIndex} 个值`;
input.dataset.index = fieldIndex; // 用于调试/映射,非必需
// 实时监听变化,自动更新 words 数组(推荐)
input.addEventListener('input', (e) => {
words[fieldIndex - 1] = e.target.value || '';
});
container.appendChild(input);
});
// 提交时收集所有有效值(过滤空字符串可选)
submitBtn.addEventListener('click', () => {
const validWords = words.filter(word => word && word.trim() !== '');
// 发送至后端(示例使用 Fetch API)
fetch('/api/sa ve-words', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ words: validWords })
})
.then(res => res.json())
.then(data => alert(`成功保存 ${data.count} 个字段!`))
.catch(err => console.error('提交失败:', err));
});
有几个细节值得注意:
* 尽量避免在提交时临时用 querySelectorAll('input') 去读取DOM——如果用户通过粘贴等方式输入且没有触发 input 事件,数据可能会漏掉。
* 建议使用 input 事件而不是 change 事件,这样能确保实时响应每一次输入。
* 如果需求里还涉及删除字段,那么 words 数组也要同步 splice 掉对应的索引,并重新调整后续元素的 dataset.index。
// server.js(需安装 express, mysql2)
const express = require('express');
const mysql = require('mysql2/promise');
const app = express();
app.use(express.json());
const pool = mysql.createPool({
host: 'localhost',
user: 'your_user',
password: 'your_pass',
database: 'your_db',
waitForConnections: true,
connectionLimit: 10
});
app.post('/api/sa ve-words', async (req, res) => {
const { words } = req.body;
if (!Array.isArray(words) || words.length === 0) {
return res.status(400).json({ error: '缺少有效字段数据' });
}
try {
const connection = await pool.getConnection();
// 使用参数化查询防止 SQL 注入
const placeholders = words.map((_, i) => `(?)`).join(', ');
const sql = `INSERT INTO words_table (content) VALUES ${placeholders}`;
await connection.execute(sql, words);
connection.release();
res.json({ success: true, count: words.length });
} catch (err) {
console.error(err);
res.status(500).json({ error: '数据库保存失败' });
}
});
app.listen(3000, () => console.log('Server running on http://localhost:3000'));
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
8