javascript
  • jquery
  • html
  • iframe
  • 2016-11-15 1 views -2 likes 
    -2

    url에서 HTML을로드하고 싶지 않기 때문에 javascript가 src = ""인 iframe 요소를 만들고 있습니다. 자바 스크립트를 사용하여 iframe의 html을 변경하고 싶습니다. 내 iframe 요소는iframe 내부에 동적 콘텐츠를 추가하는 방법 ..?

    window.onload = function() { 
        var html = ''; 
        html += '<div id="myModal" class="modal fade"><div class="modal-dialog"><div class="modal-content"><div class="modal-header">'; 
        html += '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button><h4 class="modal-title">Preview</h4></div>'; 
        html += '<div class="modal-body" style="height:450px; width:100%; margin-top: -17px; margin-left: -17px;">'; 
        html += '<iframe id="myiframe" src="" onload="editContent();" width="100%" height="100%" style="position:fixed;border-width: 0;" allowtransparency="true">'; 
        html += '</iframe></div></div></div></div>'; 
        document.body.innerHTML += html; 
    
        var iframe = document.getElementById('myiframe'), 
         iframedoc = iframe.contentDocument || iframe.contentWindow.document; 
        iframedoc.body.innerHTML = '<h1>Test h1</h1><h2>Test h2</h2><h3>Test h3</h3><h4>Test h4</h4><h5>Test h5</h5><h6>Test h6</h6>'; 
    } 
    

    이지만 iframe이 내부의 컨텐츠를 추가하지 않으며 내가 콘솔에서 찾고 경우 여전히 iframe이 비어 있습니다. 거기에 무슨 오류가 있습니까?

    +2

    코드가 제대로 작동해야합니다 (https://jsfiddle.net/oam44y0e/). 콘솔에서 오류를 확인하고 답변을 업데이트하여 문제의 작동 예제를 포함하십시오. –

    +0

    안녕하세요 @RoryMcCrossan 콘솔을보고있을 때 iframe의 본문 요소 안에는 아무 것도 없습니다. 또한 아무것도 렌더링하지 않는 브라우저 –

    +0

    window.load 이벤트 내 js 코드 writhing –

    답변

    0

    내 문제의 해결책을 발견했다. 제대로 작성되기 전에 iframe 내부에 html 데이터를 추가하려고한다. 그래서 settimeout()을 사용하고 내 js 코드를 작성하여 내부 HTML을 추가합니다. 이제는 잘 작동합니다.

    setTimeout(function() { 
        var iframe = document.getElementById('myiframe'), 
         iframedoc = iframe.contentDocument || iframe.contentWindow.document; 
        iframedoc.body.innerHTML = '<h1>Test h1</h1><h2>Test h2</h2><h3>Test h3</h3><h4>Test h4</h4><h5>Test h5</h5><h6>Test h6</h6>'; 
    },500); 
    
    관련 문제