如何使用原型在HTML中的当前位置插入元素 [英] How to insert an element at the current position in HTML using prototype

查看:134
本文介绍了如何使用原型在HTML中的当前位置插入元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您不知道父元素的ID,那么如何在当前位置动态插入HTML元素(使用原型)?我看到的所有例子都假定这个元素有一些id。

How do you insert an HTML element dynamically (using prototype) at the current position if you don't know the id of the parent element? All examples I've seen assumes the element has some kind of id.

Ie

<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>

我已经尝试使用带有$$('div')的原型last(),但是似乎没有工作(last()有时报告另一个div如果我使用库,如livepipe)。

I've tried using prototype with $$('div').last(), but that doesn't seem to work (last() sometimes reports back another div if I use libraries such as livepipe).

我真正想要的是类似于document.write ,但是使用原型而不是raw html。

What I really want is something similar to document.write, but using prototype instead of raw html.

推荐答案

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

The only way I can think of is finding the <script> element and insert the element before/after the script. The thing is, all DOM methods need a DOM node to operate on. Executing scripts that modify the DOM before the document has loaded isn't a good and safe idea.

以下链接的类似问题。


  1. JavaScript:获取当前执行的<脚本>节点?

  2. 如何引用加载当前执行脚本的脚本标签?

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

这篇关于如何使用原型在HTML中的当前位置插入元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆