javascript - 以 html 形式调用 javascript 函数是否有问题

标签 javascript html

我有一个文本框,它接受日期作为输入。我添加了“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/

相关文章:

javascript - 为什么instanceof Map返回false?

javascript - 如何在 IFRAME 中筛选跨来源的抓取?

html - html 元素上的边框或填充问题

javascript - 嵌套 UL 高度

javascript - 如何禁用 AngularJS 中的按钮?

javascript - 如何在 Angular 2 中使用 routerlink 动态生成 html 元素

html - 将变量添加到一组数组

html - 如何在 VS 2008 中用 HTML 标记快速包围文本?

PHP 处理脚本未拾取图像

javascript - 遍历对象数组?