Javascript 将 onClick 事件添加到 document.createElement("th")

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11017509/
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-08-24 04:01:50  来源:igfitidea点击:

Add onClick event to document.createElement("th")

javascripthtml-table

提问by daniel langer

I am dynamically adding columns to a table by using document.createElement("th")

我通过使用动态地将列添加到表中 document.createElement("th")

var newTH = document.createElement('th');

Is there a way to set an onClickattribute for this so a user can delete the column by clicking on the header? Any help would be great. If this is not possible, is it possible to put something in

有没有办法为此设置一个onClick属性,以便用户可以通过单击标题来删除该列?任何帮助都会很棒。如果这是不可能的,是否可以放入一些东西

newTH.innerHTML

to make it work?

让它发挥作用?

回答by trumank

var newTH = document.createElement('th');
newTH.innerHTML = 'Hello, World!';
newTH.onclick = function () {
    this.parentElement.removeChild(this);
};

var table = document.getElementById('content');
table.appendChild(newTH);

Working example: http://jsfiddle.net/23tBM/

工作示例:http: //jsfiddle.net/23tBM/

You can also just hide with this.style.display = 'none'.

您也可以使用 隐藏this.style.display = 'none'

回答by Someth Victory

var newTH = document.createElement('th');
newTH.onclick = function() {
      //Your code here
}

回答by Sirko

var newTH = document.createElement('th');
newTH.addEventListener( 'click', function(){
  // delete the column here
} );

回答by Arthur Choate

var newTH = document.createElement('th');
newTH.setAttribute("onclick", "removeColumn(#)");
newTH.setAttribute("id", "#");

function removeColumn(#){
// remove column #
}