使用JQuery向iframe添加事件处理程序

问题描述:

我想为iframe分配一个keydown事件处理程序。类似于纯JS的东西:

I want to assign a keydown event handler to an iframe. Something similar to the pure JS:

document.getElementById('iframe_id').contentWindow.addEventListener('keydown',funcName, true);

我试过:

$(document.getElementById('iframe_id').contentWindow).keydown( function() {
   // my func
});

但它不工作..请帮助!

But it does not work.. Please help!

contentWindow iframe 窗口对象。你想要 iframe 文件

contentWindow is the iframe's window object. You want the iframe's document instead:

$(document.getElementById('iframe_id').contentWindow.document).keydown(function() {
    // my func
});

请注意,我不知道jQuery如何对来自其他窗口/框架的元素做出反应。

Note that I am not sure how jQuery reacts to elements from other windows/frames.