代码之家  ›  专栏  ›  技术社区  ›  Oscar Godson

将子iframe中的事件附加到父窗口中的处理程序

  •  11
  • Oscar Godson  · 技术社区  · 14 年前

    我不能直接访问这个iframe的源代码,所以我想这样做,如果可能的话。

    我有一个由JS生成的iframe:

    <iframe name="temp_iframe" width="100%" height="95%" src="'+the_url+'"></iframe>
    

    然后

    例如,如果这不是在iframe和jQuery中:

    $('[name=temp_iframe] button').live('click',function(){
        alert('click');
        return false;
    });
    

    编辑:而且,它在同一个域上!

    2 回复  |  直到 7 年前
        1
  •  13
  •   bobince    14 年前

    使用 contents() 访问iframe中的文档对象。请注意,在一个文档中使用jQuery库来操作另一个文档通常存在一些问题,通常应该避免这样做。但是,在绑定事件的情况下,它确实起作用。

    $('[name=temp_iframe]').contents().find('button').click(function() {
        alert('click');
    });
    

    这需要加载iframe及其内容,所以在 $(window).load() live / delegate 跨文档,因为事件不会从子文档传播到其父文档。

        2
  •  3
  •   mjaque    6 年前

    document.getElementById("frameId").contentDocument.getElementById("buttonId").click();
    

    document.querySelectorAll('[name=temp_iframe]')[0].contentDocument.getElementsByTagName('button')[0].click();