选择日历日期和更新链接标签

时间:2017-11-30 18:55:28

标签: javascript jquery html date calendar

我的页面上有一个链接标签。当我点击标签时,会弹出一个日历。当我点击日历上的日期时,我希望我的链接标签以“2017年1月30日”的格式更新到该特定日期

问题是由于本地变量var dateText =...,我的标签永远不会更新,但会获得正确的格式。

如果我评论或删除日期格式部分,而不是我的标签更新到正确的日期,但不包含我正在寻找的格式。

点击日历上的特定日期时,如何使用所需的格式更新我的链接标签?

$(document).ready(function() {

  $("#dp").datepicker({
    onSelect: function(dateText, inst) {

      var dateText = new Date().toLocaleString('en-GB', {
        day: 'numeric',
        month: 'short',
        year: 'numeric'
      }).split(' ').join(' ');

      $("#datep").html(dateText);
    },
    beforeShow: function(event, ui) {
      var $link = $("#datep");
      ui.dpDiv.offset({
        top: $link.offset().top + 10,
        left: $link.offset().left + 10
      });
    }
  });

  $("#datep").click(function() {
    $("#dp").datepicker("show");
  });
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<a href="#" id="datep">Date Picker Link Label</a>
<input type="hidden" id="dp" />
<div></div>

1 个答案:

答案 0 :(得分:1)

您正在调用使用当前日期的new Date().toLocaleString(...。您遗失的只是将dateText参数传递给Date构造函数:

&#13;
&#13;
$(document).ready(function() {

  $("#dp").datepicker({
    onSelect: function(dateText, inst) {

      var dateText = new Date(dateText).toLocaleString('en-GB', {
        day: 'numeric',
        month: 'short',
        year: 'numeric'
      }).split(' ').join(' ');

      $("#datep").html(dateText);
    },
    beforeShow: function(event, ui) {
      var $link = $("#datep");
      ui.dpDiv.offset({
        top: $link.offset().top + 10,
        left: $link.offset().left + 10
      });
    }
  });

  $("#datep").click(function() {
    $("#dp").datepicker("show");
  });
});
&#13;
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<a href="#" id="datep">Date Picker Link Label</a>
<input type="hidden" id="dp" />
<div></div>
&#13;
&#13;
&#13;

相关问题