jQuery:向Datepicker添加月份 [英] jQuery: Add months to Datepicker
问题描述
借助jQuery和Datepicker,我想在今天的日期"中增加#个月.
With the help of jQuery and Datepicker, I would like to add # of months to Today's Date.
我在下面的尝试会产生意外的结果:
My attempts below produce unexpected results:
例如如果我加上0个月,则除今天的日期外还有9个月如果我增加1个月,我将再增加10个月.
e.g. If I add 0 months, I get 9 months addition to Today's date If I add 1 month, I get 10 months addition.
我已经遍历了代码,看来错误与格式有关.如果我进行硬编码:
I have stepped through the code and it seems the error is something with formatting. If I hardcode:
var ten = $('#mthschange').val();
与
var ten = 12;
工作正常
如果我测试:
var ten = $('#mthschange').val();
alert(ten);
它会提醒我:12(如果我输入12).
it will alert me: 12 (if I put in 12).
它似乎与数据类型有关.
it seems to be related to data types.
如何正确指示Datepicker向日期添加月份?
How do I correctly instruct Datepicker to add months to a date?
$(function() {
$('#mthschange').change(function() {
var ten = $('#mthschange').val();
var d = new Date();
d.setMonth(d.getMonth() + ten);
var e = ($.datepicker.formatDate('yy-mm-dd', d));
$("#res").val(e);
});
});
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Datepicker - Default functionality</title>
<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>
</head>
<body>
<p>Input Field : <input id="mthschange" type="text"></p>
<p>Output Field : <input id="res" type="text"></p>
</body>
</html>
推荐答案
您的问题是 ten
是一个字符串,而不是整数,因此在执行时
Your problem is that ten
is a string, not an integer, so when you execute
d.getMonth() + ten
您会得到类似 112
的信息,而不是 13
.更改
you get something like 112
instead of 13
. Change
var ten = $('#mthschange').val();
到
var ten = parseInt($('#mthschange').val());
并且代码正常工作:
$(function() {
$('#mthschange').change(function() {
var ten = parseInt($('#mthschange').val());
var d = new Date();
d.setMonth(d.getMonth() + ten);
var e = ($.datepicker.formatDate('yy-mm-dd', d));
$("#res").val(e);
});
});
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Datepicker - Default functionality</title>
<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>
</head>
<body>
<p>Input Field : <input id="mthschange" type="text"></p>
<p>Output Field : <input id="res" type="text"></p>
</body>
</html>
这篇关于jQuery:向Datepicker添加月份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!