我有一个文本框,它接受日期作为输入。我添加了“todaysDate4SD”和“todaysDate4ED”复选框,以便当用户希望这些文本框之一成为今天的日期时,他们可以单击相应的复选框以便为其填充(他们不需要填写文本框)今天的日期)。我将 ab 警报放在 populateTodaysDate() 函数内,所以我知道它没有到达那里。对于 JS 来说,我是个新手,所以我不确定什么语法是错误的,它没有调用这个函数。
<div id="form">
<form>
<p class="field">Start Date:<input type="text" id="start" name="start" /></p>
<p class="field"><input type="checkbox" id="todaysDate4SD" name="todaysDate4SD"
onclick="populateTodaysDate(todaysDate4SD,start);" />
<p class="field">End Date:<input type="type" id="end" name="end" /></p>
<p class="field"><input type="checkbox" id="todaysDate4ED" name="todaysDate4ED"
onclick="populateTodaysDate(todaysDate4ED,end);" />
<p class="field"><input type="checkbox" id="includeEndDate" name="includeEndDate" checked="true" />
Include the end date in the calculation</p>
<p class="submitbttn"><input type="button" value="Submit" onclick="calculate();" /></p>
</form>
onclick populateTodaysDate 调用中的参数(即 TodaysDate4ED,end)是字符串。我试图传递 id,以便在函数中我可以使用 document.getElementById(id) ...我之前尝试在实际元素中 passind (通过将此 document.getElem... 放在 onclick 调用中,但这并没有也不起作用)。
下面是我认为由于某种原因没有被调用的函数。它位于 html 页面头部的 script 标签中。
function populateTodaysDate(checkbox, dateBox) {
alert("I'm here!")
if(checkBox.checked) {
dateBox.value = dateToString(new Date()).
} else {
dateBox.value = "";
}
}
警报并不重要,只是添加来看看我是否真的进入了这个功能......
...如果有人想查看 dateToString...应该没有必要(99.98% 确定这不是问题所在)
function dateToString(d1) {
var curr_year = d1.getFullYear();
var curr_month = d1.getMonth() + 1; //Months are zero based
if (curr_month < 10) {
curr_month = "0" + curr_month;
}
var curr_date = d1.getDate();
if (curr_date < 10) {
curr_date = "0" + curr_date;
}
return curr_month + "/" + curr_date + "/" + curr_year;
}
最佳答案
您的复选框应如下所示:
<input type="checkbox" id="todaysDate4SD" name="todaysDate4SD"
onclick="populateTodaysDate(this,'start');" />
<input type="checkbox" id="todaysDate4ED" name="todaysDate4ED"
onclick="populateTodaysDate(this,'end');" />
并更新你的函数:
function populateTodaysDate(checkbox, dateBox) {
dateBox = document.getElementById(dateBox);
if(checkBox.checked) {
dateBox.value = (new Date()).toString("yyyy-MM-dd HH:mm:ss");
} else {
dateBox.value = "";
}
}
关于javascript - 以 html 形式调用 javascript 函数是否有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16751408/