为什么我的iframe把html内容当作文本?

问题描述 投票:1回答:2

为什么会这样?iframe 将我的html内容视为文本内容。

问题:我想把整个html内容和它的标签一起渲染,而不是作为文本内容。 我想把整个html和它的标签一起渲染,而不是作为一个文本。

下面的图片显示了我的问题。

enter image description here

我的代码:

$('#resultBtn').off('click');
 $('#resultBtn').on('click',function(){
 
 var html = '<p id="pclick">Click me to see Alert</p>'
  var javascript = `document.querySelector('#pclick').on('click',function(){
     alert('clicked me');
 })`;
  var bodyContent = html +`<script>${javascript}<\/script>`;


$("#result_iframe").contents().find("body").html(`${bodyContent}`);

});
#result_iframe{
   width: 400px;
   height: 200px;
   background:#eaeaed;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

 <button id="resultBtn">see Result</button>


<iframe id="result_iframe" frameborder="0"></iframe>
javascript jquery iframe
2个回答
0
投票

我不是专家,但我知道你不能在阅读文档后在文本中传递JS。在这里的编辑器中,它不工作,我不知道为什么,但在测试文件中它工作。试试这个(JS en parent)。

  <button id="resultBtn">see Result</button>
   <iframe id="result_iframe" frameborder="0"></iframe>
   <script>
     var button = document.getElementById("resultBtn");
     var iframe = document.getElementById("result_iframe");

     button.onclick = function(){
       iframe.contentDocument.body.innerHTML = "<p onclick='window.parent.showAlert()'>Click Me</p>"
     }
     function showAlert(){
       alert("Hi");
     }
   </script>

0
投票

这段代码试图将HTML内容添加到一个 iframe:

$("#result_iframe").contents().find("body").html(`${bodyContent}`);

然而,将文本结点或HTML元素添加到一个新的项目中。iframe 不支持。从 iframe的HTML5规格:

4.8.5 iframe元素

内容模式。     无

而这里是什么 没什么 在此上下文中的含义。

当一个元素的内容模型为 "无 "时,该元素必须不包含 "文本 "节点(除元素间空白外)和元素节点。

鉴于向一个 iframe 是不支持的,可能是一个好主意,使用不同的方法。


-1
投票

Semed,你的代码工作正常。确保你的脚本是在jquery插入后写的。

$('#resultBtn').off('click');
$('#resultBtn').on('click',function(){
  var html = '<p id="pclick">Click me to see Alert</p>'
  var javascript = `document.querySelector('#pclick').on('click',function(){
alert('clicked me');
})`;
  var bodyContent = html +`<script>${javascript}<\/script>`;


  $("#result_iframe").contents().find("body").html(`${bodyContent}`);
});
© www.soinside.com 2019 - 2024. All rights reserved.