我在這里有一些簡單的香草代碼。我的目標是抓取所有部分,遍歷它們并在每個部分插入一個新元素:
let sectionSign = document.createElement('p');
sectionSign.innerHTML = '§'
sectionSign.style.marginTop = '1rem'
let allSections = document.querySelectorAll('section')
allSections.forEach((section) => {
section.style.border = '1px solid red'
section.after(sectionSign)
})
style.border 只是為了確保它選擇了我想要的所有元素并且它做到了。但是,sectionSign 僅在最后一個部分之后添加,而不是在每個部分之后。我該如何解決這個問題?
uj5u.com熱心網友回復:
試試這個,你必須為每個部分創建一個新元素。
let allSections = document.querySelectorAll('section')
allSections.forEach((section) => {
let sectionSign = document.createElement('p');
sectionSign.innerHTML = '§';
sectionSign.style.marginTop = '1rem';
section.style.border = '1px solid red';
section.after(sectionSign);
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/423054.html
標籤:
