如何将事件绑定到本地iframe中的元素?

Har*_*ldo 2 javascript iframe jquery

首先,父页面和iframe都托管在同一台服务器上(我在WAMP上的localhost),所以这里的原始策略不应该是一个问题.

我无法让触发器工作.我的iframe有id iframe.

$(window).load(function(){
  //iframe ad hovers
  $('#iframe').contents().find('body div').click(function(){
    alert('do something here');
  });
}); 
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Poi*_*nty 7

我不确定浏览器是否会将"click"事件从<iframe>out 窗口上下文传播到包含窗口.加载到文档中的文档是否<iframe>有自己的jQuery副本?如果是这样,你可以试试这个:

$('#iframe').contents().$.find('body div').click(function(){
  alert('do something here);
});
Run Code Online (Sandbox Code Playgroud)

这变化使得jQuery代码<iframe>窗口处理该事件.

好吧,我认为@jAndy是正确的,应该按原样运行 - 你必须确保框架中的文档已加载.试试这个:

$('#iframe').load(function() {
  $(this).contents().find('body div').click(function() { alert("hi"); });
});
Run Code Online (Sandbox Code Playgroud)