首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用JavaScript创建动态创建字段的JSON对象数组

使用JavaScript创建动态创建字段的JSON对象数组
EN

Stack Overflow用户
提问于 2021-11-25 11:08:56
回答 2查看 42关注 0票数 0

下面是动态生成的字段。为了简单起见,我删除了不必要的代码。单击按钮时,请帮助我生成一个JSON对象数组

代码语言:javascript
复制
<div class="row sertile">
                          
              <input type="hidden" class="form-control parType" value="Service">
              <input type="hidden" class="form-control id" value="144">
              <input type="hidden" class="form-control serviceName" value="Full face">
              <input type="hidden" class="form-control mrp" value="200">
              <input type="hidden" class="form-control dis" value="0">
              <input type="hidden" class="form-control dur" value="30">

  </div>

<div class="row sertile">
                          
              <input type="hidden" class="form-control parType" value="Service">
              <input type="hidden" class="form-control id" value="124">
              <input type="hidden" class="form-control serviceName" value="Half face">
              <input type="hidden" class="form-control mrp" value="200">
              <input type="hidden" class="form-control dis" value="0">
              <input type="hidden" class="form-control dur" value="30">

  </div>

我需要如下输出:

代码语言:javascript
复制
[
 {
  parType: 'Service', 
  id: 144,
  serviceName: 'Full Face',
  ...
 }, 
 {
  parType: 'Service', 
  id: 124,
  serviceName: 'Half Face',
  ...
 },
 ...
]
EN

回答 2

Stack Overflow用户

发布于 2021-11-25 11:41:49

我已经找到了解决这个问题的方法。感谢大家的帮助。

代码语言:javascript
复制
        function createJSON() {
          jsonObj = [];
          $(".sertile").each(function() {

            var id = $(this).find("#serId").val();
            var name = $(this).find("#serName").val();

            item = {}
            item["title"] = id;
            item["email"] = name;

            jsonObj.push(item);
          });

          console.log(jsonObj);
        }
票数 0
EN

Stack Overflow用户

发布于 2021-11-25 11:34:44

你试过使用Element.getElementsByClassName()吗?

一种想法可能是在div中添加一个标记,并通过文档上的getElementsByClassName获取它们,然后循环遍历它们以按其类获取每个字段,并将其添加到一个对象中,然后如果需要,可以将其转换为string json

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70110049

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档