使用 Javascript 的动态 HTML
我正在使用 javascript 在 HTML 中动态构建输入元素网格。每行有 4 个输入元素,用户可以根据需要添加或删除行。每次他们添加或删除一行时,我都会动态重建网格。
我的问题是在我第二次构建网格后,我无法引用任何元素。我相信 DOM 现在每个元素都出现了 2 次同名,并且当我尝试按名称引用时会感到困惑。
我的问题:有没有办法重置元素名称的 DOM 列表,以便在每个动态构建中“重新启动”的名称仍然是唯一的?
I am using javascript to dynamically build a grid of input elements in HTML. Each row has 4 input elements and the user can add or delete rows as they need. Each time they add or delete a row, I am rebuilding the grid dynamically.
My problem is after I build the grid a second time, I cannot reference any of the elements. I believe the DOM now has 2 occurances of each element with the same name, and is confused when I try to reference by name.
My question: is there any way to reset the DOM listing of element names, so on each dynamic build the "resued" name is still unique ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以在每次创建网格时为节点 id 指定不同的唯一前缀,并在每次通过 id 引用节点时包含该前缀。
或者您可以更改代码,不要每次都重建整个网格。
不过,我认为可能是您误诊了问题,或者我没有正确理解您的问题。如果您记得在插入新的表元素之前从文档中删除旧的表元素,则 id 或名称应该不会发生冲突。
You can give the node ids a different unique prefix every time you create the grid and include that each time you reference a node by id.
Or you can change your code not to rebuild the whole grid every time.
However I think it might be that you've misdiagnosed the problem or I don't understand your question correctly. If you remember to remove the old table element from the document before inserting the new one, there should be no conflict over the ids or names.
为什么要重建?在 DOM 中插入新行或删除现有行。不是问题。
下面是一个使用原型添加/删除行的示例 html 文件:
将其复制/粘贴到新文件并尝试。我相信您可以轻松地将功能移植到您正在使用的任何库中。
Why rebuild? Insert a new row in the DOM or delete the existing one. Not a problem.
Here is a sample html file that uses prototype to add / delete rows:
Copy / paste it to a new file and try it. I am sure you can easily port the functionality to whatever lib you are using.