gpt4 book ai didi

javascript - insertAdjacentHTML 未正确插入传递的字符串

转载 作者:行者123 更新时间:2023-12-03 01:12:38 25 4
gpt4 key购买 nike

我想在特定元素后插入 html,但 insertAdjacentHTML 不允许我先添加结束标签。

如果我这样做

elm.insertAdjacentHTML('afterend', '</div><section class="block">');

预期结果是

 <element></element></div><section class="block">

返回的结果

 <element></element><section class="block"></div>

有办法解决这个问题吗?

编辑:

基本上我想做的是循环遍历每个元素并将它们分成两个 div

 <div class="column">
<div class="block">block 1</div>
<div class="block">block 2</div>
<div class="block">block 3</div>
<div class="block">block 4</div>
<div class="block">block 5</div>
<div class="block">block 6</div>
<div class="block">block 7</div>
<div class="block">block 8</div>
</div>

预期结果

 <div class="column">
<div class="block">block 1</div>
<div class="block">block 2</div>
<div class="block">block 3</div>
<div class="block">block 4</div>
</div>
<div class="column">
<div class="block">block 5</div>
<div class="block">block 6</div>
<div class="block">block 7</div>
<div class="block">block 8</div>
</div>

JS

const blocks = document.querySelectorAll(".block");
let half = Math.ceil(blocks.length / 2 - 1);
blocks[half].insertAdjacentHTML('afterend', '</div><div class="column">');

最佳答案

如果我满足您的要求,这就是您想要做的:

elm.parentNode.insertAdjacentHTML('afterend', '<section class="block"></section>');

如果 div 不是直接父元素,您可能需要使用 Element.closest(selector) 来代替:

elm.closest('div.myDiv').insertAdjacentHTML('afterend', '<section class="block"></section>');

更新

您已经进一步详细说明了您的要求,这是如何在 Javascript 中实现的:

const blocks = [...document.querySelectorAll('.block')];

const middle = Math.ceil(blocks.length / 2 - 1);

const column = document.querySelector('.column');

const parent = document.querySelector('.parent');

const col1 = document.createElement('div');
col1.className = 'column';
const col2 = document.createElement('div');
col2.className = 'column';

blocks.forEach((block, index) => {
if (index <= middle) {
col1.appendChild(block)
} else {
col2.appendChild(block)
}
})

parent.removeChild(column)
parent.appendChild(col1);
parent.appendChild(col2);
.column+.column {
color: green;
}
<div class="parent">
<div class="column">
<div class="block">block 1</div>
<div class="block">block 2</div>
<div class="block">block 3</div>
<div class="block">block 4</div>
<div class="block">block 5</div>
<div class="block">block 6</div>
<div class="block">block 7</div>
<div class="block">block 8</div>
</div>
</div>

生成的 DOM:

Resulting DOM

关于javascript - insertAdjacentHTML 未正确插入传递的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52150384/

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