javascript - Jquery通过id作为变量查找元素
问题描述
我使用 jquery 从服务器获取对象列表。每个对象都有两个字段id
和singleValue
(在服务器上它们都是字符串)。我想遍历列表并将值放入正确的元素中。
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>
id
from 对象是输入的 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"
}
]
}
解决方案
根据作者的代码,我假设预期的输出是[{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);
推荐阅读
- webpack - 从 Expo 的 createWebpackConfigAsync 配置 Webpack 时,WebStorm 不解析别名
- python-3.8 - 无法在诗歌中添加插件
- php - PhpMailer,如何为多个 addCC 电子邮件地址正确写入变量值?
- flutter - 修复需要在 Flutter 中扩展的 Widget 的最小宽度
- csv - 将具有结构的 Hive 表写入 TSV 文件
- python - 我可以在 python 模块上运行 line_profiler 吗?
- c# - 如何创建自定义结构(或类)类型的应用程序设置参数?
- ruby - 有没有办法改变小提琴的工作目录?
- plsql - 需要删除/插入该表中的相应行,因为出现重复数据-PLSQL
- javascript - 使用 Java 和 Typescript 进行 AES 加密/解密