2012-02-08 40 views
0

我试图记录属于一行的对象的位置。所以最后我需要一个全面的对象,它包含行和行内“com”的位置。这是我的代码:(g是一个全局对象)试图使用括号表示法访问深度值

g = {comPos:""} 

$(".Com").draggable({ 
      start: function(event, ui) { 
       var thisRow = $(this).closest("div[id^='step']"); 
       g.thisRowID = thisRow.attr("id"); 
       g.thisComID = $(this).attr("id"); 
       console.log(g.thisComID); //returns the id value 
      }, 
      stop: function(event, ui) { 
       var thisX = event.pageX; 
       var thisY = event.pageY; 
       var thisComPos = { 
        id: g.thisRowID, 
        x: thisX, 
        y: thisY 
       } 
       g.comPos[g.thisRowID][g.thisComID] = thisComPos; //undefined 
      } 
     }); 

这是一个被抛出的错误:

"TypeError: Cannot set property 'com1' of undefined" 

使用括号标记我有不确定的回报方式。我究竟做错了什么?请告诉我,如果你需要更多的代码,我已经粘贴了我认为相关的部分。

+0

我想我们需要看到g'的'定义。什么是返回undefined,它是'g.comPos [g.thisRowID] [g.thisComID]'? – 2012-02-08 20:25:26

+0

你可以包含“g”对象吗? – 2012-02-08 20:27:22

+0

@JulianD .-- g只包含一个空的“comPos”。 'g = {comPos:“”}' – dopatraman 2012-02-08 20:29:02

回答

0

当你

g.comPos[g.thisRowID][g.thisComID] = thisComPos; 

它是真正用于查找g.comPos[g.thisRowID],渐渐导致的对象,然后插入一个新的属性值的快捷方式。换句话说,它是

var myTemporaryObject = g.comPos[g.thisRowID]; 
myTemporaryObject[g.thisComID] = thisComPos; 

相当于我猜,如果你打破了你这样的代码,那么这中间的“myTemporaryObject”将是零。

使中间对象被填充必须明确地发生;它不会仅仅通过魔法出现在那里。

尝试像

g.comPos[g.thisRowID] = g.comPos[g.thisRowID] || {} //create an empty intermediate object if necessary 
g.comPos[g.thisRowID][g.thisComID] = thisComPos; 
+0

@ JacobM - 我尝试了您的解决方案,并清理了相同的错误:“TypeError:无法设置未定义的属性”com1“ – dopatraman 2012-02-08 20:31:18

+0

@JacobM - 空的对象工作,但缺点是,我每次拖动东西时清理行对象 – dopatraman 2012-02-08 20:35:04

+0

不清楚你的意思是关于清理行对象 - 使用OR语法的想法('g.comPos [g .thisRowID] || {}')是,如果行对象已经定义,它仍然存在,但是如果它没有定义,我们定义它为空。您可能想要定义g和comPos对象:'g = g || {}; g.comPos = g.comPos || {}' – 2012-02-08 20:46:31