javascript 如何在表格中创建复选框列?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26738599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 06:25:29  来源:igfitidea点击:

How to create checkbox column in the table?

javascriptdomdom-manipulation

提问by Michael

I am dynamically creating a table using JavaScript code below:

我正在使用下面的 JavaScript 代码动态创建一个表:

function CreatTable(data) {

    var tablearea;
    var table;
    var thead;
    var tr;
    var th;

    tablearea = document.getElementById('ShowDataID');
    table = document.createElement('table');
    thead = document.createElement('thead');
    tr = document.createElement('tr');

    for (var i = 0; i < data.length; i++) {
        var headerTxt = document.createTextNode(data[i]);
        th = document.createElement('th');
        th.appendChild(headerTxt);
        tr.appendChild(th);
        thead.appendChild(tr);
    }

    table.appendChild(thead);

    for (var i = 1; i < 4; i++) {
        tr = document.createElement('tr');
        tr.appendChild(document.createElement('td'));
        tr.appendChild(document.createElement('td'));
        tr.appendChild(document.createElement('td'));
        tr.cells[0].appendChild(document.createTextNode('John'));
        tr.cells[1].appendChild(document.createTextNode('McDowell'));
        tr.cells[2].appendChild(document.createTextNode('[email protected]'));

        table.appendChild(tr);
    }
    tablearea.appendChild(table);
}
</script>

When I create table I also need to create checkbox column in the table above.

创建表时,我还需要在上表中创建复选框列。

Any idea how I can implement it using JavaScript? Or related link?

知道如何使用 JavaScript 实现它吗?或者相关链接?

回答by dosaki

I'm not sure if this is what you're asking:

我不确定这是否是您要问的:

var checkbox = document.createElement("INPUT");
checkbox.type = "checkbox";

and then you'd append checkboxto each row in order to form a new column.

然后您将附加checkbox到每一行以形成一个新列。

See this fiddle: http://jsfiddle.net/qeeu18g1/3/I added comments where I added things.

看到这个小提琴:http: //jsfiddle.net/qeeu18g1/3/我在我添加的东西的地方添加了评论。

(is this a duplicate of this question?)

(这是这个问题的重复吗?)

回答by cн?dk

Use the following JS code:

使用以下 JS 代码:

var x = document.createElement("INPUT");
x.setAttribute("type", "checkbox");
x.setAttribute("name", "city");
x.setAttribute("value", "London");
x.setAttribute("id", 1);

And place it whereever you want to add it.

并将其放置在您想要添加的任何位置。

See more at HTML DOM Input Checkbox Object

在 HTML DOM 输入复选框对象中查看更多信息