JS闭包——依赖回调的多个日期选择器初始化/调用

JS Closure - Multiple date picker initializations / invocations that relies on callback

本文关键字:选择器 日期 初始化 调用 闭包 依赖 回调 JS      更新时间:2023-09-26

我如何使用闭包正确调用和初始化以下脚本上的多个日期选择器(Bootstrap日期选择器),以便我不必为每个日期选择器id重复我的函数?

http://www.daterangepicker.com/是我使用的选择器

cb_helper <----这是我尝试使用闭包失败的地方,以便我将"记住"传入的id…

我做错了什么?

JS

 $(function() {
     var start = moment().subtract(29, 'days');
     var end = moment();
     var idVal = "";
    function cb(start, end) {
        $(idVal + ' span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
    }

    function cb_helper(id, start, end)
    {
      (function(){
          idVal = id;
          cb(start, end);
      })();
    }
    function init(id){
      $(id).daterangepicker({
        startDate: start,
        endDate: end,
        ranges: {
           'Today': [moment(), moment()],
           'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
           'Last 7 Days': [moment().subtract(6, 'days'), moment()],
           'Last 30 Days': [moment().subtract(29, 'days'), moment()],
           'This Month': [moment().startOf('month'), moment().endOf('month')],
           'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
        }
      }, cb);
    }
    init("#reportrange_profitability");
    init("#reportrange_volume");
    cb_helper("#reportrange_profitability", start, end);
    cb_helper("#reportrange_volume", start, end);
  });
$(function() {
    var start = moment().subtract(29, 'days');
    var end = moment();

    function cb(idVal) {
        return function(start, end) {
            $(idVal + ' span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
        }
    }

    function init(id, start, end) {
        $(id).daterangepicker({
            startDate: start,
            endDate: end,
            ranges: {
                'Today': [moment(), moment()],
                'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                'Last 30 Days': [moment().subtract(29, 'days'), moment()],
                'This Month': [moment().startOf('month'), moment().endOf('month')],
                'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
            }
        }, cb(id));
    }
    init("#reportrange_profitability", start, end);
    init("#reportrange_volume", start, end);
});