如果可能的话,我可以单击 iframe 中的某个元素并让它在呈现它的页面上执行某个功能吗?
例如:
<div class="page">
<iframe class="frame">[... the source will render: <div class="clickme"></div>...]
</iframe>
...同时,回到主页...
<script>
$(".clickme").click(function(){
alert('clicked');
});
</script>
</div>
edit另外,我忘了提到 iframe 的 src 在页面加载后会发生变化,这可能是一个障碍!
它似乎对我不起作用,我在这里找不到合适的答案/问题。谢谢!
如果用户单击 iframe 中的某个项目会导致父级中触发一个函数,则以下内容将起作用,假设您有一个名为doStuff
在父级中:
window.top.doStuff();
当然,这需要iframe的域与父页面的域相匹配。
如果需要跨域怎么办?
如果您需要跨域通信,那么 HTML5 postMessage 函数将允许您将父页面注册为 iframe 的监听器,从而允许 iframe 向父页面传递消息。
在父 HTML 中,注册一个侦听器:
// register to listen for postMessage events
window.addEventListener("message", receiveMessage, false);
// this is the callback handler to process the event
function receiveMessage(event)
{
// you're responsible for your own security. Make sure requests are
// coming from domains you whitelist!
if (event.origin !== "http://example.org:8080")
return;
if(event.data == "click!") {
// do your stuff on the parent page here
}
}
在 iframe HTML 页面中:
// pass the string "click!" to the parent page, where the receiveMessage
// handler will take action when it sees the message matches.
top.window.postMessage("click!", targetOrigin);
See 窗口.postMessage https://developer.mozilla.org/en/DOM/window.postMessage更多细节。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)