简体   繁体   English

访问iframe元素并将其更新为DOM

[英]Access iframe element and update it to the DOM

I want to access page2.html element containing img tag and update it to the page1.html img tag or replace img of page1.html to page2.html img. 我想访问包含img标签的page2.html元素,并将其更新为page1.html img标签,或将page1.html的img替换为page2.html img。 Both the files are on same domain so no need to worry about cross domain origin policy. 这两个文件都在同一个域中,因此无需担心跨域源策略。

// Page1.html

   <body>

   <img id="someimage1" src="./captcha.asp"></img>
   <iframe src="page2.html"></iframe>
   <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
   <script type="text/javascript>
       var getImg = $('iframe').contents().find('#someimage2').html();
       $('#someimage1').replaceWith('<img>' getImg '</img>');
   </script>
   </body>

I get DOM Update as [object] [Object] 我将DOM更新作为[对象] [对象]

// Page2.html

   <body>

   <img id="someimage2" src="./captcha.asp"></img>
   <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>

   </body>

I will help you with one Vanilla JS solution, you can modify it to JQuery: 我将为您提供一个Vanilla JS解决方案,您可以将其修改为JQuery:

First check if your IFrame contains any document at all 首先检查您的IFrame是否包含任何文档

Firefox and Chrome Solution Firefox和Chrome解决方案

var frame  = document.getElementById("frame");
if(frame.contentDocument) {
 // get the inner Document
 var innerDocument = frame.contentDocument;
 var img = innerDocument.getElementsByTagName("img")[0];
}

IE Solution IE解决方案

var frame  = document.getElementById("frame");
if(frame.contentDocument) {
 // get the inner Document
 var innerDocument = frame.contentWindow.document;
 var img = innerDocument.getElementsByTagName("img")[0];
}

When you got the image the rest is just a DOM manipulation operations. 当您获得图像时,剩下的只是DOM操作操作。

Get Inner Document Body 获取内部文档正文

var getIFrameCOntent = function(iFrame) {
  var frame = document.querySelector(iFrame);
  var innerDocument = frame.contentDocument || frame.contentWindow.document;

   var body = innerDocument.getElementsByTagName("body")[0];  

  return body;
}

Simple Solution 简单的解决方案

var frame = document.getElementById('frame').contentWindow.document.body;
    console.log(frame.getElementsByTagName("img")[0]);

try this code.... 试试这个代码...。

page1.html...
<html>
<head>
    <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
</head>
<body>
    <div id="imgAA">
    </div>
    <img src="img1.jpg" style="width:100px;" id="imgBB"/>
    <script>
            $(document).ready(function(){
                $("#imgAA").load("page2.html",function(data){
                    $("#imgBB").attr("src",$("#imgAA").find("img").attr("src"));
                });
            });
    </script>
</body>

page2.html...
<body>
   <img src="img2.jpg" style="width:50px;" id="img2"></img>
</body>

try this and tell me it is work fine.... 试试这个,告诉我一切正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM