2012-01-14 61 views
2

所以我有下面這段代碼:如何從JavaScript中的對象鍵值返回數組?

var structures = { 

    loginStructure : function(){ 

     return structure = [ 
      '<form name="',opts.formClass,'" class="',opts.formClass,'" method="post" action="#">', 
       '<fieldset class="',opts.fieldsWrapper,'">', 
        '<fieldset class="',opts.userWrapper,'">', 
         '<label for="',opts.userInt,'" class="',opts.userLbl,'"><img src="',opts.userIcon,'" alt="',opts.userName,'" /></label>', 
         '<input type="text" name="',opts.userInt,'" class="',opts.userInt,'" placeholder="',checkNameLenght(opts.userName,namesLenght.userNameLenght,16,'Username'),'" value="" autocomplete="off" />', 
        '</fieldset>', 
        '<fieldset class="',opts.passWrapper,'">', 
         '<label for="',opts.passInt,'" class="',opts.passLbl,'"><img src="',opts.passIcon,'" alt="',opts.passName,'" /></label>', 
         '<input type="password" name="',opts.passInt,'" class="',opts.passInt,'" placeholder="',checkNameLenght(opts.passName,namesLenght.passNameLenght,16,'Password'),'" value="" autocomplete="off" />', 
        '</fieldset>', 
        '<fieldset class="',opts.btnWrapper,'">', 
         '<button type="submit" name="',opts.btnInt,'" class="',opts.btnInt,'">',checkNameLenght(opts.btnName,namesLenght.btnNameLenght,7,'Login'),'</button>', 
        '</fieldset>', 
       '</fieldset>', 
       '<div class="toogle-button">', 
        '<ul class="inside">', 
         '<li class="toogle"><a><img src="assets/gfx/toogle.png" alt="Back" /></a></li>', 
        '</ul>', 
       '</div>', 
      '</form>', 
      '<div class="toogle-buttons">', 
      '</div>' 
     ]; 
    } 

} 

這將返回(如果我做console.log(structures.loginStructure))只是一個function()。有沒有一種方法可以讓它返回我在那裏的實際數組?

它的目的是將多個數組定義爲對象鍵,如果有可能返回這樣的東西,因爲它看起來更容易。還是有更好的方法來做到這一點?

+0

順便說一句,這與jQuery無關 - 但將其標記爲表示您可能正在使用jQuery--這可能會提示其他人提供jQuery相關答案。 – ziesemer 2012-01-14 20:19:10

+0

是的,我也使用jQuery,實際上這段代碼是jQuery插件的一部分。 – Roland 2012-01-14 20:25:48

+0

如果所有變量都被正確定義,似乎在這裏工作得很好:http://jsfiddle.net/jfriend00/ekZVE/。 – jfriend00 2012-01-14 20:53:00

回答

4

你想:

structures.loginStructure(); 

structures.loginStructure僅僅是剛剛返回函數的引用,而不是執行該功能並返回其結果。將()添加到其末尾以執行它並返回其結果。

或者,也許更好,不要把它寫成函數。只需聲明loginStructure: ['<form name...。基本上,只需刪除function(){return structure =。這裏需要注意的一個重要區別是,opts的任何值都會被立即評估,而不是延遲到稍後纔會執行的函數 - 所以請不要盲目更新您的代碼。

+0

而不是'',opts.formClass,''+ + opts.formClass +''? – Roland 2012-01-14 20:21:51

+0

我試過了,但它給了我一個錯誤,在我的代碼行上,我有'return this.each(function(){.......',why? – Roland 2012-01-14 20:24:47

+0

@Roland - 我認爲我們需要看到更多的代碼來準確地回答這個問題,我認爲這可能適用於一個新的問題。 – ziesemer 2012-01-14 20:27:07

相關問題