在javascript中创建复选框

时间:2014-06-13 08:57:53

标签: javascript checkbox

我尝试使用Javascript创建一个复选框,当它被点击时,将显示格式化时间(hh:mm:ss)。我遇到的问题是它甚至没有创建复选框,我也不知道为什么。这是我的代码:

document.write("<form><input type="checkbox"></form>")

任何人都可以给我一个问题所在的提示吗?

3 个答案:

答案 0 :(得分:4)

首先,你没有逃避报价;

document.write("<form><input type=\"text\"></form>")这将创建文本框

试试这个

document.write('<form><input type="checkbox"></form>');

答案 1 :(得分:2)

在您的代码中,您不会转义引号。

你应该逃避报价。

document.write('<form><input type="checkbox"></form>')

但我建议您不要使用document.write(),因为它是not a good practice取代整个文档

因此,您应该尝试使用javascript动态创建元素。

试试这段代码:

var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.name = "name";
checkbox.value = "value";
checkbox.id = "id";
document.body.appendChild(checkbox);

答案 2 :(得分:1)

Working Fiddle

var cb = document.createElement('input');
cb.type = "checkbox";
cb.name = "name";
cb.value = "value";
cb.id = "id";
cb.addEventListener("click", showTime, false);

var lbl = document.createElement('label')
lbl.htmlFor = "id";
lbl.appendChild(document.createTextNode("show time"));

var container = document.getElementById('container');
container.appendChild(cb);
container.appendChild(lbl);

var sp = document.getElementById('time');

function showTime() {
    if (this.checked) {
        var today = new Date()
        sp.innerHTML = today.toString();
    } else {
        sp.innerHTML='';
    }
}