-
03-10-2019 - |
题
在我的JS中,我有一个称为box_object的对象。看起来像这样:
({ id:"3",
text:"this is a box object",
connection_parent:["1", "2"],
connection_child:["5", "6"],
connectiondata_child:{
0:{id:"5", linepoint:"bottom"},
1:{id:"6", linepoint:"bottom"}},
connectiondata_parent:{
0:{id:"1", linepoint:"top"},
1:{id:"2", linepoint:"top"}}
})
现在,我想将一些位置值添加到box_object.connectiondata_parent。使用jQuery,我可以使用.each()方法。所以我尝试了,但是失败了。在我的功能中,我执行以下操作:
$(box_object.connectiondata_parent).each(function(it, obj){
if(typeof(obj[it]) != "undefined" && obj[it].linepoint == "top"){
var point_position_top = new Object();
point_position_top.left = startingpoint_left;
point_position_top.top = startingpoint_top;
obj[it].position = point_position_top;
}else if(typeof(obj[it]) != "undefined" && obj[it].linepoint == "bottom"){
var point_position_bottom = new Object();
point_position_bottom.left = startingpoint_left;
point_position_bottom.top = startingpoint_bottom;
obj[it].position = point_position_bottom;
}else{}
});
功能后,我的Box_Object看起来像这样:
({ id:"3",
text:"this is third box",
connection_parent:["1", "2"],
connection_child:["5", "6"],
connectiondata_child:{
0:{id:"5", linepoint:"bottom"},
1:{id:"6", linepoint:"bottom"}},
connectiondata_parent:{
0:{id:"1", linepoint:"top", position:{left:500, top:104}},
1:{id:"2", linepoint:"top"}}
})
似乎只将值写入第一个“值”。为什么?
解决方案
根据评论 这里 经过 卡尔·瑞德伯格(Karl Swedberg), , 在 $(selector).each()
这应用于DOM元素。对于普通对象或数组,请使用 jquery.each().
也许那是给您一个问题的原因。
其他提示
以下代码样本将不用为每个功能使用框架,而是在嵌套元素中的适当条目中迭代并执行请求的转换。
function assert(cond, msg) {
if (!cond) {
throw msg + " ... failed";
}
}
// assumed globals
var startingpoint_left = 500;
var startingpoint_top = 104;
var startingpoint_bottom = 50; // never shown in sample but referenced
var idx;
for (idx in box_object.connectiondata_parent) {
if (box_object.connectiondata_parent.hasOwnProperty(idx)) {
if (box_object.connectiondata_parent[idx]) {
box_object.connectiondata_parent[idx].position = {
"left": startingpoint_left,
"top": box_object.connectiondata_parent[idx].linepoint === "top" ? startingpoint_top : startingpoint_bottom
};
}
}
}
assert(box_object.connectiondata_parent[0].position.top === 104, "index 0 top ");
assert(box_object.connectiondata_parent[0].position.left === 500, "index 0 left");
assert(box_object.connectiondata_parent[1].position.top === 104, "index 1 top ");
assert(box_object.connectiondata_parent[1].position.left === 500, "index 1 top ");
不隶属于 StackOverflow