Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用javascript从表中删除列_Javascript_Html - Fatal编程技术网

使用javascript从表中删除列

使用javascript从表中删除列,javascript,html,Javascript,Html,我需要使用javascript自动从html表中删除一列。该表是使用框架从csv文件自动创建的,因此我无法修改它(例如添加id,等等)。我通过向列标题添加一个链接来删除该列,并单击它来删除该列,但我找不到在页面加载时自动执行该操作的方法。我不熟悉javascript,所以请尝试为傻瓜解释一下 函数closestByTagName(el,标记名){ while(el.tagName!=标记名){ el=el.parentNode; 如果(!el){ 返回null; } } 返回el; } 函数列

我需要使用
javascript
自动从
html
表中删除一列。该表是使用框架从
csv
文件自动创建的,因此我无法修改它(例如添加
id
,等等)。我通过向列标题添加一个链接来删除该列,并单击它来删除该列,但我找不到在页面加载时自动执行该操作的方法。我不熟悉
javascript
,所以请尝试为傻瓜解释一下

函数closestByTagName(el,标记名){
while(el.tagName!=标记名){
el=el.parentNode;
如果(!el){
返回null;
}
}
返回el;
}
函数列(链接){
var idx=2,
table=closestByTagName(链接,“表”),
rowCount=table.rows.length;
对于(变量i=0;i

全名
国家
位置
手机
电子邮件
马格纳斯
危地马拉
拉卡约
22
马格纳斯。gaylord@example.com
菲比·菲斯特
危地马拉
拉卡约
23
ylittel@example.net
泰德·约翰斯顿教授
危地马拉
拉卡约
24
srau@example.org
安娜贝尔·奥尔蒂斯
危地马拉
拉卡约
25
达莫尔。walker@example.org
阿德拉·席勒四世夫人
危地马拉
拉卡约
26
杰丁。dibbert@example.com

由于您的所有列都有一个特定的
,使用
ES6
可能的解决方案是:

document.querySelectorAll(".col2").forEach(col => col.remove());
或采用标准方法:

var cols = document.querySelectorAll(".col2");

for (var i = 0; i < cols.length; i++)
{
    cols[i].remove();
}
var cols=document.queryselectoral(“.col2”);
对于(变量i=0;i
例子:
window.onload=function()
{
var cols=document.queryselectoral(“.col2”);
对于(变量i=0;icol.remove());
}

全名
国家
位置
手机
电子邮件
马格纳斯
危地马拉
拉卡约
22
马格纳斯。gaylord@example.com
菲比·菲斯特
危地马拉
拉卡约
23
ylittel@example.net
泰德·约翰斯顿教授
危地马拉
拉卡约
24
srau@example.org
安娜贝尔·奥尔蒂斯
危地马拉
拉卡约
25
达莫尔。walker@example.org
阿德拉·席勒四世夫人
危地马拉
拉卡约
26
杰丁。dibbert@example.com

Shidersz的答案很好,但也值得注意的是,您可以使用单个CSS规则而不是JavaScript:

.col2{
显示:无;
}

全名
国家
位置
手机
电子邮件
马格纳斯
危地马拉
拉卡约
22
马格纳斯。gaylord@example.com
菲比·菲斯特
危地马拉
拉卡约
23
ylittel@example.net
泰德·约翰斯顿教授
危地马拉
拉卡约
24
srau@example.org
安娜贝尔·奥尔蒂斯
危地马拉
拉卡约
25
达莫尔。walker@example.org
阿德拉·席勒四世夫人
危地马拉
拉卡约
26
杰丁。dibbert@example.com

您是否尝试过直接从加载事件调用delColumn?例如,
delColumn(document.querySelectorAll(“th”)[2])
?非常有用,谢谢!!!!!因为您的所有列都有一个特定的类,所以您可以使用
document.querySelectorAll(“.col2”).forEach(node=>node.remove())@Shidersz哇,我一整天都在努力解决这个问题,而你只用了一分钟和一行就成功了!!!!谢谢!!!由于这个问题特别要求javascript,似乎作为注释而不是答案更好……这也是一个很好的选择,唯一需要注意的是DOM元素仍将存在于表中,但如果目标只是不直观地显示数据,那就很好了+1@Jordan运行感谢我会使用这个,但我不能像Shidersz提到的那样在DOM中使用元素。无论如何,这是一个非常好的答案+1.