使用iframe的内容在页面上执行jquery .click()
如果可能,我可以单击iframe中的元素并在其呈现的页面上执行某个function吗?
例如:
[... the source will render: ...]
…同时,回到主页……
$(".clickme").click(function(){ alert('clicked'); });
编辑也,我忘了提到页面加载后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);
有关更多详细信息,请参见window.postMessage 。
您可以使用content()访问iframe中的元素
$('.frame').contents().find('.clickme').each(function(){ $(this).click(function(){ //this is .clickme //enter code here }) });
请注意,如果iframe的src来自不同的域,您将被拒绝访问。
你可以在iframe中调用一个函数,
window.frames['iframeName'].yourFunction();
并在Iframe中