【问题标题】:perform jquery .click() on page using iframe's content使用 iframe 的内容在页面上执行 jquery .click()
【发布时间】:2012-05-27 02:09:50
【问题描述】:

如果可能,我可以单击 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 中的项目时,您的意思是用户会点击 iframe 中的项目,还是您以编程方式点击 iframe 中的项目?
  • 它加载不同的
    但无论加载哪个,它们都将具有相同的类...我将它用作搜索框,因此在搜索后它会加载新的 src结果在 iframe 中
  • 抱歉不知道你的意思,但是是的,用户会点击 iframe 中的一个对象

标签: javascript jquery iframe parent-child


【解决方案1】:

你可以在 iframe 中调用函数,

window.frames['iframeName'].yourFunction();

在 iframe 中

    <script>
              $(".clickme").click(function(){
                      yourFunction();
               });

             function yourFunction(){
              alert('clicked');
             }
   </script>

【讨论】:

  • 谢谢!所以我需要为特定的 iframe 设置函数,然后我可以在 iframe 中使用该函数?
  • 请注意,这仅在 iframe 的域与父文档的域匹配时才有效。
【解决方案2】:

您可以使用 content() 访问 iframe 中的元素

$('.frame').contents().find('.clickme').each(function(){
   $(this).click(function(){ //this is .clickme
     //enter code here
   })
});

注意如果 iframe 的 src 来自不同的域,您将被拒绝访问。

【讨论】:

  • 谢谢,我仍然无法解决这个问题...如果 iframe 的内容在页面加载后发生变化,这有关系吗?
【解决方案3】:

如果用户单击 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

【讨论】:

  • 谢谢!它现在有效!我没有像我应该使用的那样使用好的 'ol javascript onclick。 @jmort253,我很高兴继续为您提供所有这些积分哈哈...感谢您最近的所有帮助!
猜你喜欢
相关资源
最近更新 更多
热门标签