2 回答

TA貢獻1811條經(jīng)驗 獲得超4個贊
有點不清楚實際上問題出在哪里 - 如果只是為每一行添加一個可以在 PHP 循環(huán)中輕松完成的數(shù)字(設(shè)置一個變量并在每次循環(huán)迭代時遞增。)
進一步的混亂,因為根據(jù)問題,可以自動添加或刪除行,但尚不清楚這是如何發(fā)生的或為什么會發(fā)生。javascript 不正確,HTML 也不正確,因為每個都設(shè)置了重復(fù)的 ID 屬性TD~ 如果確實需要,一個更好的選擇可能是使用dataset屬性,但是可以使用querySelector&/or來完成定位 DOM 中的特定元素querySelectorAll
下面的代碼使用一段簡單的 Javascript ( & querySelectorAll ) 來查找表格中所有相關(guān)的表格單元格,并為每個單元格分配一個整數(shù)。由于"table which automatically adds rows or removes them"如果添加或刪除了一行,整數(shù)將不再準確 - 因此使用MutationObserver監(jiān)視 DOM 以了解對表的更改。
我希望這能提供一些幫助。
document.addEventListener('DOMContentLoaded',(e)=>{
// specifically target ALL first cells within the table and assign some content - an integer.
const callback = function() {
Array.from( document.querySelectorAll( 'tr > td:first-of-type' ) ).forEach( ( td, i )=>{
td.textContent=i + 1;
})
};
// determine what the observer will react to
const config = {
attributes:false,
childList:true,
characterData:false,
subtree:true
};
// monitor the table for changes
( new MutationObserver( callback ) ).observe( document.querySelector('table'), config );
// number the table rows at page load
callback();
// utility function to find table row
const getrow=function(e){
let n=e.target;
while(n.tagName!='TR')n=n.parentNode;
return n;
};
// a simple event listener bound to the `delete` links which will remove entire table row
// the `MutationObserver` will be triggered by a row deletion and the rows will be re-indexed
Array.from( document.querySelectorAll('td > a') ).forEach( a=>{
a.onclick=function(e){
e.preventDefault()
let tr=getrow(e);
tr.parentNode.removeChild( tr );
}
})
})
<table>
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Surname</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>fred</td>
<td>bloggs</td>
<td><a href="#">Delete</a></td>
</tr>
<tr>
<td></td>
<td>jim</td>
<td>smith</td>
<td><a href="#">Delete</a></td>
</tr>
<tr>
<td></td>
<td>john</td>
<td>doe</td>
<td><a href="#">Delete</a></td>
</tr>
<tr>
<td></td>
<td>mike</td>
<td>hunt</td>
<td><a href="#">Delete</a></td>
</tr>
</tbody>
</table>
如果這有過于復(fù)雜的事情,并且您只需要在每一行上顯示一個數(shù)字并且表格在頁面加載后不會改變,那么要么使用前面提到的 PHP 添加,或者您甚至可以只使用 CSS

TA貢獻1860條經(jīng)驗 獲得超8個贊
const rows = document.querySelectorAll 在 TR 上的效果怎么樣,然后 .length 將是下一個數(shù)字(因為頭部的 tr 基本上是你通常會做的 +1 來增加數(shù)字)
添加回答
舉報