gpt4 book ai didi

javascript - JS Closure - 依赖于回调的多个日期选择器初始化/调用

转载 作者:行者123 更新时间:2023-12-03 05:37:39 25 4
gpt4 key购买 nike

如何使用闭包在以下脚本上正确调用和初始化多个日期选择器(引导日期选择器),以便我不必为每个日期选择器 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);
});

关于javascript - JS Closure - 依赖于回调的多个日期选择器初始化/调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40663785/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com