9

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);

I tried:

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

But it does not work.. Please help!

4

4 回答 4

15

contentWindowiframewindow对象。你想要iframe'sdocument代替:

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

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

于 2009-02-15T03:22:28.967 回答
4

只是要记住一点:据我所知,如果 iframe 内容是跨域的,这将永远不会起作用。您最终会遇到权限错误: Permission denied for http://... to get property HTMLDocument.nodeType from http://...。浏览器将父子 dom 权限限制在同一个域中。

于 2010-04-08T19:19:16.773 回答
0

$ 函数取代了对 document.getElementById 的需要

$('iframe_id').contentDocument.keydown(function() {
   // logic
});
于 2009-02-14T19:40:53.757 回答
0

这对我有用:

$('#iframe_id').contents().keydown(function() {
    // my func
});
于 2014-07-14T03:30:58.180 回答