首页 > 解决方案 > 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

标签: jqueryeach

解决方案


您不能以您尝试的方式将对象属性作为字符串值提供给父对象。

要解决此问题,请在循环中创建子对象,如下所示:

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()更合适。


推荐阅读