d-_*_*_-b 2 javascript iframe jquery parent-child
如果可能,我可以单击iframe中的元素并在其呈现的页面上执行某个功能吗?
例如:
<div class="page">
<iframe class="frame">[... the source will render: <div class="clickme"></div>...]
</iframe>
Run Code Online (Sandbox Code Playgroud)
...同时,回到主页......
<script>
$(".clickme").click(function(){
alert('clicked');
});
</script>
</div>
Run Code Online (Sandbox Code Playgroud)
编辑也,我忘了提到页面加载后iframe的src发生了变化,这可能是一个障碍!
它似乎不适合我,我在这里找不到合适的答案/问题.谢谢!
如果用户单击iframe中的某个项应该导致在父项中触发函数,那么假设您doStuff在父项中调用了一个函数,则以下内容将起作用:
window.top.doStuff();
Run Code Online (Sandbox Code Playgroud)
当然,这要求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
}
}
Run Code Online (Sandbox Code Playgroud)
在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);
Run Code Online (Sandbox Code Playgroud)
有关更多详细信息,请参见window.postMessage.