将动态值添加到插件选项中

时间:2015-06-03 10:20:38

标签: jquery

我正在使用jquery插件 http://amsul.ca/pickadate.js/date/

我处于需要向插件添加动态选项/设置值的情况。

工作设置示例:

$input = $('.datepicker').pickadate({
              disable: [
                  { from: [2015,5,10], to: [2015,5,17] }
                 ]
           });

我想从数据库创建from和to date,这是我的代码:

booking_dates是一个数组输出:

 Array
    (
        [0] => Array
            (
                [0] => 2015-06-02
                [1] => 2015-06-07
            )

        [1] => Array
            (
                [0] => 2015-06-10
                [1] => 2015-06-15
            )

        [2] => Array
            (
                [0] => 2015-06-16
                [1] => 2015-06-20
            )

    )

var booking_dates = ajax_object.booking_dates;
                var data = '';
                for(i = 0; i < booking_dates.length; i++ ) {
                    k = 0;

                    var from = booking_dates[i][k].split('-');
                    var to = booking_dates[i][++k].split('-');

                    if(i == 0) {
                        data = '{ from: [' + from[0] + ',' + (--from[1]) + ',' + from[2] + '], to: [' + to[0] + ','+ (--to[1]) + ',' + to[2] + '] }';
                    } else {
                        data = data + ', ' + '{ from: [' + from[0] + ',' + (--from[1]) + ',' + from[2] + '], to: [' + to[0] + ','+ (--to[1]) + ',' + to[2] + '] }';
                    }
                } 

                    alert (data); //{ from: [2015,5,15], to: [2015,5,20]}

数据变量结果为:{ from: [2015,5,15], to: [2015,5,20] }

但是当我用设置替换数据时,它不起作用:

不工作:

  $input = $('.datepicker').pickadate({
                            disable: [
                               data
                            ]
                    });

它是一个字符串因此不起作用?或者我必须以不同的方式创建选项字符串?

2 个答案:

答案 0 :(得分:1)

您需要创建一个对象数组,而不是创建一个字符串

var booking_dates = ajax_object.booking_dates;
var data = [];
for (i = 0; i < booking_dates.length; i++) {
    k = 0;

    var from = booking_dates[i][k].split('-');
    var to = booking_dates[i][++k].split('-');

    data.push({
        from: [from[0], --from[1], from[2]],
        to: [to[0], --to[1], to[2]]
    })
}

alert(data);

$input = $('.datepicker').pickadate({
    disable: data
});

答案 1 :(得分:0)

你应该创建一个合适的数组并传递它。

var booking_dates = ajax_object.booking_dates;
var data = [];
for (i = 0; i < booking_dates.length; i++) {
    k = 0;
    var from = booking_dates[i][k].split('-');
    var to = booking_dates[i][++k].split('-');
    data.push({
        from: [from[0],  (--from[1]) , from[2]],
        to: to[0] , (--to[1]) , to[2]
    })   
}

然后使用

$('.datepicker').pickadate({
    disable: data
});