2011-09-10 44 views
6

我掙扎着從函數調用返回數組返回數組 - 下面的代碼:JQUERY +從功能

///////////// Generic Functions 
function spotJoinPosition() { 
    var pos = { 
       offset: $('div#spotJoinSite').offset(),         
       width: $('div#spotJoinSite').width(), 
       height: $('div#spotJoinSite').height() 
    } 
    return(pos); 
} 


     var positionData = spotJoinPosition(); 
     alert(positionData); 
     alert(positionData[width]); 

當我提醒positionData我得到[對象] [對象],然後不確定的。

建議?

回答

6

alert(positionData[width]);

這提醒在positionData的密鑰,並且使用可變width作爲鍵。您尚未定義名爲width的變量,因此它實質上是查找positionData[undefined]。你想要的是positionData.widthpositionData['width'],但這裏沒有引號的理由。

僅當您使用非字母數字字符的鍵時才需要引用。 positionData['some-key']有效,但positionData.some-key是語法錯誤,因爲變量中不能有-

此外,你的代碼應該是錯誤的,因爲寬度沒有定義在任何地方。我擔心你的代碼中有一個全局定義的width變量。

1

這是因爲positionData是變量width未定義變量width一個對象(你從spotJoinPosition返回的對象)和包含的值是不存在的對象。

您想要positionData.widthpositionData['width']

See the MDN docs on member operators.

+1

實際,'positionData [width]'輸出'undefined'的原因是因爲'width' *是在某處定義的,但是'width'的值不是一個有效的鍵在他的'positionData'對象中。 – Chris

0

嘗試:

alert(positionData.offset); 
    alert(positionData.width); 
    alert(positionData.height); 
0

如果你真的想返回一個array而不是object一個通用的功能,你可能要修改爲以下內容:

///////////// Generic Functions 
function spotJoinPosition(selector) { 
    var el = $(selector), 
     result = [el.offset(), el.width(), el.height()]; 

    return(result); 
} 

var positionArray = spotJoinPosition("#spotJoinSite"); 
alert(positionArray[0]); // outputs the position 
alert(positionArray[1]); // outputs the width