jQuery:如何在包含' this&#39 ;?的函数外返回一个值

时间:2017-10-14 15:25:12

标签: javascript jquery

我的代码当前console.log是文档准备好后变量timestamp的值。每次在timestamp函数中更新变量.datepicker()时是否有一种方法可以运行它而不在函数本身中?



$("document").ready(function() {
  var timestamp;
  $("#startDate").datepicker({
    onSelect: function(e) {
      var dateAsObject = $(this).datepicker("getDate");
      timestamp = dateAsObject.getTime();
      console.log("user selected: " + timestamp);
      return timestamp;
    }
  });
  console.log("test: " + timestamp);
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

<form action="">
  <label for="startDate">Select a date:</label>
  <input type="text" id="startDate" name="startDate">
</form>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

我可能会误解你的问题,但是你不能只在onSelect事件处理程序中调用另一个函数吗?

Here's a JSFiddle显示了这一点,我认为这正在做你需要的事情。

$("document").ready(function() {
    var timestamp;
    $("#startDate").datepicker({
        onSelect: function(e) { 
            var dateAsObject = $(this).datepicker( "getDate" ); 
            timestamp = dateAsObject.getTime(); 
            console.log("user selected: " + timestamp);
            otherFunction();
        }
    });

    function otherFunction() {
        console.log("test: " + timestamp);
    }
});