【问题标题】:How to make array inside array data for custom jQuery Function?如何为自定义 jQuery 函数在数组数据中制作数组?
【发布时间】:2013-08-31 17:25:38
【问题描述】:

我正在寻找一些在自定义 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);

【问题讨论】:

  • 您在第二个代码 sn-p 的第 4 行缺少 first_word 周围的引号

标签: javascript jquery html function jquery-plugins


【解决方案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);

【讨论】:

    【解决方案2】:

    从您的代码来看,您似乎忘记将 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);
    

    【讨论】:

      猜你喜欢
      • 2011-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-29
      • 1970-01-01
      • 1970-01-01
      • 2011-10-02
      • 1970-01-01
      相关资源
      最近更新 更多