微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从没有框架的 DomElement 节点获取对象

如何解决从没有框架的 DomElement 节点获取对象

我的页面中有一个元素:

<form>

<div data-id="x">
    <label>field 1</label>
    <input name="field1" type="text" value="Foo" />
    <label>field 2</label>
    <input name="field2" type="number" value="5" />
</div>

<div data-id="y">
    <label>field 1</label>
    <input name="field1" type="text" value="Foo" />
    <label>field 2</label>
    <input name="field2" type="number" value="5" />
</div>

...other 100 inputs...
</form>

我正在寻找这样的 javascript 脚本:

var theElement = document.querySelector('[data-id="x"]');
var myObject = theElement.toObject();

并且对象必须看起来像

{"field1":"Foo","field2":5}

我无法使用 FormData 策略,因为我需要来自一个非常大的表单的非常小的数据集,但它就像一个“部分 FormData”。

我在问是否存在一种标准方法来转换对象中 HTMLElement 的内容,例如 FormData。

PS:如有必要,我也可以使用数据属性

解决方法

实际上没有标准的快速方法来完成这项任务。

解决方案是迭代输入和选择:

<script>
  let myObj = {};
  let element = document.querySelector('[data-id="x"]');
  element.querySelectorAll('input').forEach(el=> {
     // check the type
     // the property is : el.name
     // the value must be : el.value for text/number/email...
     // the value for the type="checkbox" is according to checked attribute
  });
  element.querySelectorAll('select').forEach(sel=> {
      // if multiple choise => create an array of selected options
      // if single => check the selected option's value
  });

</script>

这是我使用的代码(简化)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。