如何使用jQuery在iFrame中插入HTML内容
下面是使用jQuery将HTML内容插入iFrame的任务。要做到这一点,我们可以使用jQuery的 contents() 方法。
.contents()方法:它返回所有的直接子节点,包括选定元素的文本和注释节点。
语法:
$(selector).contents()
步骤:
- 在正文部分找到iframe。
- 获取要插入正文部分的iframe中的值
- 将数值放在iframe中
jQuery代码显示这种方法的工作情况:
示例 1:
<!DOCTYPE html>
<html>
<head>
<title>How to insert HTML content
into an iFrame using jQuery?</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js">
</script>
<style type="text/css">
textarea,
iframe {
display: block;
margin: 10px 0;
}
iframe {
width: 500px;
border: 1px solid #000000;
}
</style>
</head>
<body>
<center>
<h1 style="color:green;">
GeeksForGeeks
</h1>
<h3>
How to insert HTML content into an iFrame using jQuery
</h3>
<textarea rows="2" cols="40" style="text-align:center;">
GEEKSFORGEEKS - A computer science portal for geeks.
</textarea>
<button type="button" onclick="updateIframe()">
Click to Insert
</button>
<iframe style="text-align:center;" id="myframe"></iframe>
<script type="text/javascript">
function updateIframe() {
var myFrame = ("#myframe").contents().find('body');
var textareaValue =("textarea").val();
myFrame.html(textareaValue);
}
</script>
</center>
</body>
</html>
输出:
在点击按钮之前:
点击按钮后:
示例 2:
<!DOCTYPE html>
<html>
<head>
<title>How to insert HTML content
into an iFrame using jQuery?</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js">
</script>
<style type="text/css">
iframe {
width: 500px;
border: 1px solid #000000;
}
</style>
</head>
<body>
<center>
<h1 style="color:green;">
GeeksForGeeks
</h1>
<h3>How to insert HTML content
into an iFrame using jQuery</h3>
<h4>Text to be insert : "GEEKSFORGEEKS
- A computer science portal for geeks."</h4>
<iframe style="text-align:center;" id="iframe">
</iframe>
<script>
("#iframe").ready(function() {
var body =("#iframe").contents().find("body");
body.append(
'GEEKSFORGEEKS - A computer science portal for geeks.');
});
</script>
</center>
</body>
</html>
输出: