Javascript范围:回调函数抛出“今天不是函数”

时间:2019-05-20 01:22:45

标签: javascript jquery

我编写了以下代码,但今天不想重复两次(今天),所以我尝试在afterAdd之后的回调函数中编写它,但没有用。为什么回调函数无法检测到它?

<script type="text/javascript">
    var today = $(document).ready( function() {
        var todayDate = new Date();
        todayDate.setMinutes(todayDate.getMinutes() - todayDate.getTimezoneOffset());
        $('input[name="purchase_date"]').val(todayDate.toISOString().slice(0,10));
    });
    $(".addform .repeatable").repeatable({
        addTrigger: ".add",
        deleteTrigger: ".del",
        template: "#form_item",
        afterAdd: today
      });
    </script>

2 个答案:

答案 0 :(得分:3)

首先创建today作为函数。然后调用$(document).ready(today),并按照常规在代码中使用today

var today = function() {
  var todayDate = new Date();
  todayDate.setMinutes(todayDate.getMinutes() - todayDate.getTimezoneOffset());
  $('input[name="purchase_date"]').val(todayDate.toISOString().slice(0, 10));
};
$(document).ready(today);
$(".addform .repeatable").repeatable({
  addTrigger: ".add",
  deleteTrigger: ".del",
  template: "#form_item",
  afterAdd: today
});

答案 1 :(得分:2)

替换

var today = $(document).ready( function() {
    var todayDate = new Date();
    todayDate.setMinutes(todayDate.getMinutes() - 
    todayDate.getTimezoneOffset());
    $('input[name="purchase_date"]').val(todayDate.toISOString().slice(0,10));
});

使用

var today = function() {
    var todayDate = new Date();
    todayDate.setMinutes(todayDate.getMinutes() - 
    todayDate.getTimezoneOffset());
    $('input[name="purchase_date"]').val(todayDate.toISOString().slice(0,10));
};
$(document).ready(function() {
    today();
});

这将创建“今日”功能,并在文档准备就绪时运行它。