我有一个函数想要获取今天日期的星期数,但是单击按钮后我无法在文本框中打印该值。我是javascript新手,并且已经调试了好几个星期。请帮助
function getWeekNumber(d) {
d = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()));
d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay()||7));
var yearStart = new Date(Date.UTC(d.getUTCFullYear(),0,1));
var weekNo = Math.ceil(( ( (d - yearStart) / 86400000) + 1)/7);
return [d.getUTCFullYear(), weekNo];
document.getElementById("week").value = getWeekNumber(new Date());
}
<td>WEEK: </td>
<td><input type="text" value= "" style= "width: 230px; padding-left: 3px" id="week" name="week"></td>
<input type="button" value="Get Week" onclick= "getWeekNumber()">
答案 0 :(得分:2)
首先,函数“ getWeekNumber()”在被调用时需要参数d,但是当您在输入按钮上单击时调用它时,则不提供该参数。我认为,您应该为单击输入按钮时设置一个事件侦听器,然后从那里调用getWeekNumber()函数并将其“ new Date()”作为参数d传递,因此它看起来像下面的代码中我添加了事件监听器。
您还从内部调用了函数本身,但是在一个多余的return语句之后进行了调用。取而代之的是,您应该像我一样获得结果weekNo并将某个div的innerHTML设置为其。我认为您不应该尝试填写输入框,因为这似乎并不常见。我将其更改为div,以使过程更简单:
let get_week_button = document.getElementById("get_week");
get_week_button.addEventListener("click", function() {
getWeekNumber(new Date());
});
function getWeekNumber(d) {
d = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()));
d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay() || 7));
var yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
var weekNo = Math.ceil((((d - yearStart) / 86400000) + 1) / 7);
document.getElementById("week").value = weekNo;
}
<td>WEEK: </td>
<td>
<input type="text" value= "" style= "width: 230px; padding-left: 3px" id="week" name="week">
</td>
</tr>
<input id="get_week" type="button" value="Get Week">