2013-08-31 51 views
-3

我正在尋找一些教程,使自定義jQuery函數中的數組數據,但我找不到任何。你能告訴我如何在數組裏面爲jQuery函數創建一個數組嗎?我想打電話給我的功能是這樣的:如何在自定義jQuery函數的數組數據中創建數組?

$(this).myPlugin({ 
    data_first: '1', 
    data_second: { 
     first_word : 'Hello', second_word : 'World' 
    } 
}); 

我的功能腳本

(function($) { 
    $.fn.myPlugin = function(data) { 
     return this.each(function() { 
      alert(data['data_first']+' bla bla '+ data['data_second'][first_word]); 
     }); 
    } 
})(jQuery); 
+0

你對你的第二個代碼段的4行的丟失各地'first_word'報價 –

回答

1

這就是所謂的對象,而不是一個數組,你可以訪問它object1.object2_name.object3_name

(function($) { 
    $.fn.myPlugin = function(data) { 
     console.log(data); 
     return this.each(function() { 
      console.log(data.data_first + ' blah - ' + data.data_second.first_word); 
     }); 
    } 
})(jQuery); 
0

從你的代碼,它看起來像你忘了引號括兩種或first_word你不小心用方括號而不是點運算符。

添加引號:

(function($) { 
    $.fn.myPlugin = function(data) { 
     return this.each(function() { 
      alert(data['data_first']+' bla bla '+ data['data_second']['first_word']); 
     }); 
    } 
})(jQuery); 

或者使用點運算符(看起來更清潔在我看來):

(function($) { 
    $.fn.myPlugin = function(data) { 
     return this.each(function() { 
      alert(data.data_first + ' bla bla ' + data.data_second.first_word); 
     }); 
    } 
})(jQuery);