JavaScript通过变量引用对象属性报错,表单填充问题求助
解决Node对象属性读取错误:Cannot read property '0' of undefined
首先咱们先定位错误根源:你代码里写的node.attributes[i]是核心问题——你的自定义Node类根本没有attributes这个属性!那个attributes是你自己在函数里定义的数组,不是node对象的属性,所以node.attributes是undefined,你再用[i]去访问它,自然就抛出了"Cannot read property '0' of undefined"的错误。
要解决这个问题,你需要用方括号访问语法来通过属性名称字符串获取node对象的对应属性值,同时还有几个小细节需要修正,我给你整理了完整的修正代码:
function Node(parentNode, nodeID, fields, type){ this.id = nodeID; this.fields = fields; this.parent = parentNode; this.type = type; this.firstChild = null; this.lastChild = null; this.previousSibling = null; this.nextSibling = null; } var runTerminalNode = function(node, count){ var form = document.createElement('form'); form.setAttribute('method', 'GET'); form.setAttribute('action', '/table/'); form.setAttribute('target', '_blank'); var attributes = ['id', 'fields', 'type']; // 改用for...of循环更安全,避免遍历到数组原型上的额外属性 for (const attrName of attributes) { var input = document.createElement('input'); input.type = 'hidden'; input.name = attrName; // 关键修正:用方括号语法通过属性名字符串获取node的属性值 input.value = node[attrName]; form.appendChild(input); } // 别忘了把表单添加到DOM并提交,否则表单不会生效 document.body.appendChild(form); form.submit(); } var nodeObject = allNodes[nodeID]; // 修复函数调用:之前是赋值语句,不是函数调用 runTerminalNode(nodeObject, 0);
几个关键修改点说明:
- 属性访问方式修正:把
node.attributes[i]改成node[attrName],这样就能通过attributes数组里的属性名字符串,正确读取node对象对应的id、fields、type属性值。 - 循环方式优化:用
for...of遍历数组比for...in更可靠,因为for...in会遍历数组原型链上的可枚举属性,可能导致意外问题,而for...of只遍历数组本身的元素。 - 函数调用修复:你之前写的
runTerminalNode = (nodeObject, 0);是赋值语句,不是函数调用,改成runTerminalNode(nodeObject, 0);才能正确执行函数。 - 表单提交补充:创建表单后需要把它添加到DOM中,再调用
submit(),否则表单不会被提交到服务器。
这样修改后,就能正确把node对象的指定属性值填充到表单的隐藏输入框里了。
内容的提问来源于stack exchange,提问作者jarsushi
相关产品推荐
相关产品推荐

