为什么会这样?iframe
将我的html内容视为文本内容。
问题:我想把整个html内容和它的标签一起渲染,而不是作为文本内容。 我想把整个html和它的标签一起渲染,而不是作为一个文本。
下面的图片显示了我的问题。
我的代码:
$('#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>
解决方案:
我不是专家,但我知道你不能在阅读文档后在文本中传递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>