前端JS/DOM:将Task类元素的id与value转为POST请求对象的最优方案
解决方案:生成任务数据对象用于POST请求
实现步骤
- 使用
document.querySelectorAll('#schedule .task')精准选中目标容器内所有class为task的元素(限定在#schedule内避免选中其他无关元素) - 遍历元素集合,以元素
id为键、value属性值为值构建JSON对象 - 将生成的对象传入已有的
postJSON函数完成请求
完整代码实现
在现有JS代码中添加以下函数,并在需要提交数据时调用:
// 生成任务数据对象 function getTaskData() { // 获取所有目标元素 const taskElements = document.querySelectorAll('#schedule .task'); // 构建数据对象 const taskData = Array.from(taskElements).reduce((acc, element) => { acc[element.id] = element.getAttribute('value'); // 如果后端期望数值类型而非字符串,可改为: // acc[element.id] = Number(element.getAttribute('value')); return acc; }, {}); return taskData; } // 提交数据示例 async function submitTaskData() { const data = getTaskData(); await postJSON(data); }
代码说明
querySelectorAll('#schedule .task'):精准定位目标容器内的任务元素,避免全局选择引发的意外问题Array.from():将DOM元素集合(NodeList)转换为数组,方便使用数组遍历方法reduce():高效遍历并构建目标对象,比forEach写法更简洁- 可选转换:如果后端要求接收数值类型(0/1)而非字符串,可将
getAttribute结果转为Number类型
现有代码优化建议
原mouseClick函数重复调用document.getElementById(elementId),可优化为:
function mouseClick(elementId) { const element = document.getElementById(elementId); let elementValue = element.getAttribute("value"); if(elementValue == 0) { element.style.backgroundColor = "green"; element.setAttribute("value", "1"); // 统一用字符串保持属性值类型一致 } else { element.style.backgroundColor = "white"; element.setAttribute("value", "0"); } }
内容的提问来源于stack exchange,提问作者IoT-Practitioner
相关产品推荐
相关产品推荐

