gpt4 book ai didi

javascript - 如何使用原型(prototype)在 HTML 中的当前位置插入元素

转载 作者:行者123 更新时间:2023-11-28 21:22:43 27 4
gpt4 key购买 nike

如果您不知道父元素的 id,如何在当前位置动态插入 HTML 元素(使用原型(prototype))?我见过的所有示例都假设元素具有某种 id。

<script>
function addSomeHtmlAtCurrentPosition()
{
current_element = ...; // Magic?
current_element.insert(...);
}
</script>
<div>
<script>
addSomeHtmlAtCurrentPosition();
</script>
<!-- should insert something here... -->
</div>
<div>
<script>
addSomeHtmlAtCurrentPosition();
</script>
<!-- ... and then here -->
</div>

我尝试过将原型(prototype)与 $$('div').last() 一起使用,但这似乎不起作用(如果我使用 livepipe 等库,last() 有时会报告另一个 div)。

我真正想要的是类似于 document.write 的东西,但使用原型(prototype)而不是原始 html。

最佳答案

我能想到的唯一方法是找到 <script> 元素并在脚本之前/之后插入该元素。问题是,所有 DOM 方法都需要一个 DOM 节点来操作。在文档加载之前执行修改 DOM 的脚本并不是一个好的且安全的想法。

下面链接了类似的问题。

  1. JavaScript: get the current executing <script> node?
  2. How may I reference the script tag that loaded the currently-executing script?

关于javascript - 如何使用原型(prototype)在 HTML 中的当前位置插入元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5850477/

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