使用iframe的内容在页面上执行jquery .click() [英] perform jquery .click() on page using iframe's content

查看:556
本文介绍了使用iframe的内容在页面上执行jquery .click()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果可能的话,我可以点击iframe中的元素并让它在呈现的页面上执行一个功能吗?

If possible, can I click on an element in an iframe and have that perform a function on the page it is rendered on?

例如:

<div class="page">

    <iframe class="frame">[... the source will render: <div class="clickme"></div>...] 
    </iframe>

...同时,返回主页......

...meanwhile, back on the main page...

    <script>
          $(".clickme").click(function(){
                 alert('clicked');
           });
    </script>
</div>

编辑还有,我忘了提到iframe的src在之后发生了变化页面加载,这可能是一个障碍!

edit also, I forgot to mention that the iframe's src changes after the page loads, this could be an obstacle!

它似乎对我不起作用,我在这里找不到合适的答案/问题。谢谢!

It doesn't seem to work for me and I couldn't find an appropriate answer/question here. Thanks!

推荐答案

如果用户点击iframe中的某个项目会导致在父级中触发一个函数,那么以下内容假设您在父级中有一个名为 doStuff 的函数,它将起作用:

If the user clicking on an item in the iframe should result in a function firing in the parent, then the following will work, assuming you have a function called doStuff in the parent:

window.top.doStuff();

当然,这要求iframe的域与父页面的域匹配。

Of course, this requires the domain of the iframe to match the domain of the parent page.

如果您需要跨域域通信,然后HTML5 postMessage函数将授权您将父页面注册为iframe的监听器,允许iframe将消息传递到父页面。

If you require cross-domain communication, then the HTML5 postMessage function will empower you to register the parent page as a listener to the iframe, allowing the iframe to pass messages to the parent page.

在父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 了解更多详情。

这篇关于使用iframe的内容在页面上执行jquery .click()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆