gpt4 book ai didi

javascript - rowIndex 返回 -1

转载 作者:行者123 更新时间:2023-11-30 08:11:59 26 4
gpt4 key购买 nike

我正在使用 greasemonkey 脚本并使用以下代码更新表格。我附上了 table 的图片。但是当我点击 delete 时,rowIndex 为所有行返回 -1。我不明白为什么它返回 -1。

table = document.getElementById( 'keys-table' );
if ( !table ) return;
table.innerHTML = '';


// header
row = document.createElement( 'tr' );
th = document.createElement( 'th' );
th.innerHTML = "Group"; row.appendChild( th );
th = document.createElement( 'th' );
th.innerHTML = "Key"; row.appendChild( th );
th = document.createElement( 'th' );
th.innerHTML = " "; row.appendChild( th );
table.appendChild( row );

// keys
for ( i = 0 ; i < keys.length ; i++ ) {
row = document.createElement( 'tr' );
td = document.createElement( 'td' );
td.innerHTML = keys[i][0];
row.appendChild( td );
td = document.createElement( 'td' );
td.innerHTML = keys[i][1];
row.appendChild( td );
td = document.createElement( 'td' );

button = document.createElement( 'input' );
button.type = 'button';
button.value = 'Delete';
button.addEventListener( "click", function(event) {
DeleteKey( event.target.parentNode.parentNode.rowIndex,event.target);
}, false );
td.appendChild( button );
row.appendChild( td );

table.appendChild( row );
}

enter image description here

最佳答案

tr元素想要在 <tbody> 中元素。

通常浏览器会自动插入一个,但如果确实插入了,您将用...清除它

table.innerHTML = '';

如果你确定原始表有一个<tbody> ,然后这样做...

table = document.getElementById( 'keys-table' );
if ( !table ) return;

var tbody = table.tBodies[0];
tbody.innerHTML = '';

...然后将这些行附加到 tbody , 它会起作用。


旁注,但我个人建议使用 DOM 方法而不是 innerHTML 来删除旧行.

var tbody = table.tBodies[0];
while( tbody.firstChild )
tbody.removeChild( tbody.firstChild );

var tbody = table.tBodies[0];
while( tbody.rows[0] )
tbody.deleteRow( tbody.rows[0] );

似乎更合适。

关于javascript - rowIndex 返回 -1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8966589/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com