首页 > 解决方案 > Jquery通过id作为变量查找元素

问题描述

我使用 jquery 从服务器获取对象列表。每个对象都有两个字段idsingleValue(在服务器上它们都是字符串)。我想遍历列表并将值放入正确的元素中。

for(var i=0;i<response.listOfObjects.length;i++){
    $(response.listOfObjects[i].id).val(response.listOfObjects[i].singleValue);
}

运行此代码没有任何反应。列表有正确的值(检查它alert("id: " + response.listOfObjects[i].id + " singleValue: " + response.listOfObjects[i].singleValue);

我也尝试过

$('#' + response.listOfObjects[i].id).val(response.listOfObjects[i].singleValue);

但仍然无法正常工作。

如何解决这个问题?

@EDIT html 看起来像:

<div class="field-group" style="display: block;" original-title="" title="">
   <label for="customfield_13307">PCN</label>
   <input class="textfield text long-field" id="customfield_13307" name="customfield_13307" maxlength="254" type="text" value="">
   <div class="description">EPCN</div>
</div>

idfrom 对象是输入的 id 。

@EDIT 我使用了 JSON.stringify(response):

    {
   "name":"ATB",
   "listOfObjects":[
      {
         "id":"customfield_13305",
         "type":"single",
         "singleValue":"21766"
      },
      {
         "id":"customfield_13307",
         "type":"Text",
         "singleValue":" aaaa"
      },
      {
         "id":"customfield_13308",
         "type":"Text",
         "singleValue":" bbbb"
      }
   ]
}

标签: javascriptjqueryhtml

解决方案


根据作者的代码,我假设预期的输出是[{id:singleValue}]. 在这种情况下,我建议您使用非常适合您的Array.reduce()方法。我尝试在代码中添加一些注释:

const response = { // sample response for testing purpose
  listOfObjects: [{
      id: 'id1',
      singleValue: 1
    },
    {
      id: 'id2',
      singleValue: 2
    },
    {
      id: 'id3',
      singleValue: 3
    },
  ]
}

const mapped = response.listOfObjects.reduce(function(accumulator, currValue) {
  // here goes simple object transformation
  let obj = {};
  obj[currValue.id] = currValue.singleValue;
  accumulator.push(obj);

  return accumulator; // each iteration should retrun accumulator
}, []); // here you define starting object for your reduce method

console.log(mapped);


推荐阅读