jquery - Issue with data when created by loop
问题描述
I'm using a plugin that creates input and outputs on elements.
The normal output options are configured as follows:
outputs: {
output_0: {
label: '0',
id: 'site0_0',
},
output_1: {
label: '1',
id: 'site1_1',
},
output_2: {
label: '2',
id: 'site2_2',
},
}
When this is statically written in my script as above it works fine.
I'm now trying to dynamically create this list using a loop:
$(site).each(function(i, option) {
sites += "output_" + option + ": { label: '" + option + "', id: 'site" + option + "_" + id + "',},"
})
This produces the same data as the staically set version above : (although the layout isn't as neat )
output_0: {
label: '0',
id: 'site0_0',
},
output_1: {
label: '1',
id: 'site1_1',
},
output_2: {
label: '2',
id: 'site2_2',
},
But when I try to add it as follows I get lots of errors :
outputs: {
sites
}
jquery.flowchart.js?1565088567:545 Uncaught TypeError: Cannot read property 'replace' of undefined
at e.<computed>.<computed>._createSubConnector (jquery.flowchart.js?1565088567:545)
at e.<computed>.<computed>._createSubConnector (jquery-ui.min.js?1565088567:6)
at addConnector (jquery.flowchart.js?1565088567:516)
at e.<computed>.<computed>._getOperatorFullElement (jquery.flowchart.js?1565088567:527)
at e.<computed>.<computed>._getOperatorFullElement (jquery-ui.min.js?1565088567:6)
at e.<computed>.<computed>.createOperator (jquery.flowchart.js?1565088567:583)
at e.<computed>.<computed>.createOperator (jquery-ui.min.js?1565088567:6)
at HTMLDivElement.<anonymous> (jquery-ui.min.js?1565088567:6)
at Function.each (jquery-1.12.2.min.js?1565088567:2)
at n.fn.init.each (jquery-1.12.2.min.js?1565088567:2)
The line 545 shows:
$operator_connector_label.html(connectorInfos.label.replace('(:i)', subConnector + 1));
is it possible to create this data in a loop, and if it is how ?
Thanks
解决方案
您不能以您尝试的方式将对象属性作为字符串值提供给父对象。
要解决此问题,请在循环中创建子对象,如下所示:
var obj = {};
$(site).each(function(i, option) {
obj['output_' + option] = {
label: option,
id: 'site' + option + '_' + id
}
});
// in settings of the plugin:
outputs: obj
sites
如果它不是一个元素或元素对象数组,我还建议不要创建一个 jQuery对象。从上下文来看,它似乎只是一个普通的字符串数组,所以基本的for()
或者forEach()
更合适。
推荐阅读
- kubernetes - 在实现 HA Kubernetes 集群时将 master1 和 master2 添加到负载均衡器
- collections - 如何在集合聚合器中一次聚合 10 条记录?我想用集合拆分器拆分 100 条记录
- java - 将物品添加到库存混乱中
- google-chrome - 允许 Chrome 上的 Google Colab 域 cookie
- javascript - 从 ESLint 应用自动修复是否安全?
- r - 使用 IF 语句进行条件舍入
- react-native - 如何导出包含黑色矩形的图像(png)
- django - 由于 RDS InvalidParameterCombination,Elastic Beanstalk (Django) 部署失败
- r - 如何按 R 中的组/因子计算 NA 值的长度?
- javascript - 根据 php 中的条件更新 select 中的选定选项