【问题标题】:document.getElementbyID returns NULL for the DIV with in iFrame [duplicate]document.getElementbyID 在 iF​​rame 中为 DIV 返回 NULL [重复]
【发布时间】:2017-02-21 07:18:57
【问题描述】:

我有一个使用 iFrame 加载静态 HTML 页面的 JSP 页面。现在我正在尝试使用 jQuery 动态更改其中一个 DIV(位于静态 HTML 页面中)的对齐方式。但它不起作用。

var divEnbref = document.getElementById("enbref");
if(divEnbref!=''){
  $('#enbref').css("text-align" , "left");
}

DIV

<div id="enbref">Some Content</div>

谁能帮帮我。

【问题讨论】:

  • 只有标题中的错字。但是为什么要在加载 jQuery 时使用它呢?它永远不会是空白的。试试if($('#enbref').length&gt;0){ $('#enbref').css("text-align" , "left"); }
  • 我要为其应用样式的 DIV 在 iF​​rame 内。这行得通吗?
  • 想补充一点。静态 html 来自不同的域,并且能够在没有任何错误的情况下获取资源,即 http 代码是 200。但是当我尝试从 iFrame ref 访问文档时出现错误。
  • 如果没有代理,您将无法为所欲为。您不得更改来自不同来源的 iframe 内容

标签: jquery css iframe


【解决方案1】:

当您在iframe 中选择元素时,您需要先选择 iframe。

document.getElementById('myframe1').contentWindow.document.getElementById('enbref')

试试这个..

【讨论】:

  • 谢谢。我累了,但是当我尝试调用 var iFrameDoc = iFrame.contentDocument;或 var iFrameDoc = iFrame.contentWindow.document;由于这个 iFrameDoc 是未定义的。还有其他选择吗?
  • 您是从不同的域加载 iframe 文档吗?还是父级和 iframe 都在同一个域上?
  • iFrame 内容来自不同的域。
  • 您无法在所有浏览器中控制/修改跨域 iframe 的内容。铬。
【解决方案2】:

使用 .innerHTML 获取 div 的内容

var divEnbref = document.getElementById("enbref").innerHTML;

然后使用条件语句

if(divEnbref!=''){
  $('#enbref').css("text-align" , "left");
}

【讨论】:

    【解决方案3】:

    试试这个:

    var divEnbref = document.getElementById('enbref');
    
    document.getElementById('enbref').style.textAlign = "right";
    

    我在小提琴中试过这个:https://jsfiddle.net/mgs4y3px/

    希望对您有所帮助!

    【讨论】:

      猜你喜欢
      • 2011-11-01
      • 2011-02-07
      • 2021-03-05
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多