2 回答

TA貢獻(xiàn)1811條經(jīng)驗(yàn) 獲得超4個(gè)贊
有點(diǎn)不清楚實(shí)際上問(wèn)題出在哪里 - 如果只是為每一行添加一個(gè)可以在 PHP 循環(huán)中輕松完成的數(shù)字(設(shè)置一個(gè)變量并在每次循環(huán)迭代時(shí)遞增。)
進(jìn)一步的混亂,因?yàn)楦鶕?jù)問(wèn)題,可以自動(dòng)添加或刪除行,但尚不清楚這是如何發(fā)生的或?yàn)槭裁磿?huì)發(fā)生。javascript 不正確,HTML 也不正確,因?yàn)槊總€(gè)都設(shè)置了重復(fù)的 ID 屬性TD~ 如果確實(shí)需要,一個(gè)更好的選擇可能是使用dataset屬性,但是可以使用querySelector&/or來(lái)完成定位 DOM 中的特定元素querySelectorAll
下面的代碼使用一段簡(jiǎn)單的 Javascript ( & querySelectorAll ) 來(lái)查找表格中所有相關(guān)的表格單元格,并為每個(gè)單元格分配一個(gè)整數(shù)。由于"table which automatically adds rows or removes them"如果添加或刪除了一行,整數(shù)將不再準(zhǔn)確 - 因此使用MutationObserver監(jiān)視 DOM 以了解對(duì)表的更改。
我希望這能提供一些幫助。
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>
如果這有過(guò)于復(fù)雜的事情,并且您只需要在每一行上顯示一個(gè)數(shù)字并且表格在頁(yè)面加載后不會(huì)改變,那么要么使用前面提到的 PHP 添加,或者您甚至可以只使用 CSS

TA貢獻(xiàn)1860條經(jīng)驗(yàn) 獲得超8個(gè)贊
const rows = document.querySelectorAll 在 TR 上的效果怎么樣,然后 .length 將是下一個(gè)數(shù)字(因?yàn)轭^部的 tr 基本上是你通常會(huì)做的 +1 來(lái)增加數(shù)字)
添加回答
舉報(bào)