简体   繁体   English

Javascript范围:回调函数引发“今天不是函数”

[英]Javascript scope: Callback function throws “today is not a function”

I wrote the following code and didn't want to repeat the function (today) twice so I tried writing it within the callback function afterAdd but it didn't work. 我编写了以下代码,但今天不想重复两次(今天),所以我尝试在afterAdd之后的回调函数中编写它,但是它不起作用。 Why can't it be detected by the callback function? 为什么回调函数无法检测到它?

 <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> 

First create today as a function. 首先创建today的功能。 Then call $(document).ready(today) , and also use today in your code as per normal: 然后调用$(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
});

Replace 更换

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));
});

with

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();
});

This will create the function 'today' and run it when the document is ready. 这将创建“今天”功能,并在文档准备好后运行它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM