gpt4 book ai didi

javascript - 无法使用 node.insertBefore() 方法注入(inject) DOM 元素

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:46:01 24 4
gpt4 key购买 nike

我有一个按字母顺序排序的项目列表。这个想法是从 alphabetArr 中注入(inject)一个相应的字母<li> 之后的数组使用来自 DOMElementsArr 的 ID大批。我做错了什么?

控制台中没有错误,但它不起作用。

数组:

let alphabetArr = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p",
"q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];

let DOMElementsArr = ['8MM', ... ,'Daddy_Day_Care']

这是我的方法:

//create function that injects new element
function insertAfter(el, referenceNode) {
referenceNode.parentNode.insertBefore(el, referenceNode.nextSibling);
}

//function that loops through both arrays
function injectAllAlphabetLetters(){

//Create new element
let newEl = document.createElement('li');
newEl.className = 'titles alphabet';

for (let i = 0; i < alphabetArr.length; i++){
console.log(alphabetArr[i]);
newEl.innerHTML = alphabetArr[i][0];
}

let ref;

for (let j = 0; j < DOMElementsArr.length; j++){
console.log(DOMElementsArr[j]);
ref = document.getElementById(DOMElementsArr[j]);
}

insertAfter(newEl, ref);
}

injectAllAlphabetLetters();

最佳答案

在您当前的代码中,您只是创建一个元素,然后迭代和更新其内容,然后在下一个循环中获取元素,最后您只调用 insertAfter 函数一次并使用最后一个值。

要使其工作,您必须合并两个循环,然后将插入代码移动到循环中。

//create function that injects new element
function insertAfter(el, referenceNode) {
referenceNode.parentNode.insertBefore(el, referenceNode.nextSibling);
}

//function that loops through both arrays
function injectAllAlphabetLetters() {
// iterate until last element of minimum length array(to avoid problem in case array length are different)
for (let i = 0; i < alphabetArr.length && i < DOMElementsArr.length; i++) {
//Create new element and set properties
let newEl = document.createElement('li');
newEl.className = 'titles alphabet';
newEl.innerHTML = alphabetArr[i][0];

// get the element based on id
let ref = document.getElementById(DOMElementsArr[i]);
// call function to insert
insertAfter(newEl, ref);
}

}

injectAllAlphabetLetters();

关于javascript - 无法使用 node.insertBefore() 方法注入(inject) DOM 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55334669/

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