简体   繁体   English

Jquery按id查找元素作为变量

[英]Jquery find element by id as variable

Im using jquery to get a list of objects from the server.我使用 jquery 从服务器获取对象列表。 Every object has two fields id and singleValue (on the server both of them are Strings).每个对象都有两个字段idsingleValue (在服务器上它们都是字符串)。 I want to iterate over the list and put values in the correct elements.我想遍历列表并将值放入正确的元素中。

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

Nothing happend by running this code.运行这段代码什么也没发生。 List has correct values (checked it by alert("id: " + response.listOfObjects[i].id + " singleValue: " + response.listOfObjects[i].singleValue); )列表具有正确的值(通过alert("id: " + response.listOfObjects[i].id + " singleValue: " + response.listOfObjects[i].singleValue);

I also tried to do我也尝试做

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

but still doesn't work.但仍然不起作用。

How is it possible to solve this problem?如何解决这个问题?

@EDIT the html looks like: @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>

The id from the object is the id of the input.id从对象是输入的ID。

@EDIT I used JSON.stringify(response): @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"
      }
   ]
}

Based on author's code, I assume, that the expected output is [{id:singleValue}] .根据作者的代码,我假设预期的输出是[{id:singleValue}] In this case I suggest you to use Array.reduce() method which perfectly does work for you.在这种情况下,我建议您使用Array.reduce()方法,它非常适合您。 I've tried to add few comments in the code:我试图在代码中添加一些注释:

 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM