【问题标题】:Javascript insertBefore iframeJavascript 在 iframe 之前插入
【发布时间】:2015-08-09 18:53:33
【问题描述】:

由于我不会进入的原因,我需要在页面中使用 iframe(我知道它们已经过时等等)。我还需要使用 javascript 在 iframe 之前插入链接。

根据 W3 学校,这应该很容易:

var newItem = document.createElement("LI");       // Create a <li> node
var textnode = document.createTextNode("Water");  // Create a text node
newItem.appendChild(textnode);                    // Append the text to <li>

var list = document.getElementById("myList");    // Get the <ul> element to insert a new node
list.insertBefore(newItem, list.childNodes[0]);  // Insert <li> before the first child of <ul>

但是,这似乎适用于除 iframe 之外的每个 html 元素?

谁能解释一下如何做到这一点,或者至少为什么它不适用于 iframe。

【问题讨论】:

  • “但是,这似乎适用于除 iframe 之外的所有 html 元素?” 是什么让您认为它不适用于 iframe?在寻求帮助时,不要引用可以工作的代码,而是引用你尝试过的没有工作的代码。 insertBeforeiframes 配合得很好,所以问题出在你没有显示的代码上。

标签: javascript html iframe


【解决方案1】:
iframeElement.parentNode.insertBefore(insertedNode, iframeElement);

【讨论】:

  • 欢迎来到 Stack Overflow。虽然这段代码 sn-p 可以解决问题,但including an explanation 确实有助于提高帖子的质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
【解决方案2】:

您可以在 IFRAME 之前添加一个链接。

http://jsfiddle.net/n9a668dz/

$('<a href=#>a link</a>').insertBefore('iframe')

我在您的代码中没有看到任何 iframe

或者,如果您更喜欢纯 Javascript:

var a=document.createElement('a')
a.innerHTML='hello world'
a.href='#'

document.body.insertBefore(a,document.getElementsByTagName('iframe')[0])

http://jsfiddle.net/qd4ppmga/

【讨论】:

  • 感谢您的帮助。它似乎在 jsfiddle 中有效,但在我的网站中仍然无效。一定是页面上其他地方的代码有问题。我会调查...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多