jQuery 是一个快速、简洁的 JavaScript 库,它简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互。iframe 是 HTML 中的一个内嵌框架,允许在一个页面中嵌入另一个页面。
<iframe>
标签嵌入页面。假设我们有一个父页面 parent.html
和一个子页面 child.html
,我们希望在父页面中调用子页面的方法。
parent.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Parent Page</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<iframe id="childFrame" src="child.html"></iframe>
<button id="callChildMethod">Call Child Method</button>
<script>
$(document).ready(function() {
$('#callChildMethod').click(function() {
var iframe = document.getElementById('childFrame');
var iframeWindow = iframe.contentWindow;
if (iframeWindow && typeof iframeWindow.childMethod === 'function') {
iframeWindow.childMethod();
} else {
console.error('Child method not found');
}
});
});
</script>
</body>
</html>
child.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Child Page</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h1>Child Page</h1>
<script>
function childMethod() {
alert('Child method called!');
}
</script>
</body>
</html>
load
事件确保 iframe 加载完成后再进行操作。$('#childFrame').on('load', function() {
var iframe = document.getElementById('childFrame');
var iframeWindow = iframe.contentWindow;
if (iframeWindow && typeof iframeWindow.childMethod === 'function') {
iframeWindow.childMethod();
} else {
console.error('Child method not found');
}
});
通过以上方法,可以在父页面中成功调用子页面的方法,并解决常见的跨域和加载问题。
没有搜到相关的沙龙