jquery在iframe中侦听事件 [英] jquery listen for events in an iframe
问题描述
我正在使用jquery创建一个非常简单的富文本编辑器...我不想使用第三方。
I'm making a very simple Rich Text Editor using jquery... I don't want to use a third-party one.
我需要听对于iframe中的事件(相同的域等),从键入开始。显然我需要经常使用bind()。
I need to listen for events within an iframe (same domain etc), starting with typing. Apparently I'll need to use bind() a lot.
这就是我现在所拥有的在IE8中工作得很好(令人惊讶的是)但不是Chrome 。
This is what I've got at the moment which works fine in IE8 (amazingly enough) but not Chrome.
<script>
$(function() {
$('#text').contents().bind("keyup keydown keypress", function(e) {
var code = e.keyCode || e.which;
alert(code);
return false;
});
});
</script>
<body>
<iframe id="text" name="text" src="edit.html"></iframe>
</body>
在上面的按键事件中,我还想获得'edit.html的当前值'并用该值更新textarea ...
On the key press event above, I will also want to get the current value of 'edit.html' and update a textarea with that value...
任何帮助都会非常感激:)
Any help would be MUCH appreciated :)
许多谢谢
编辑:要进一步解释,edit.html是一个可编辑的文件,使用document.body.contentEditable = true;
to explain further, edit.html is an editable file using "document.body.contentEditable = true;"
-
编辑2:
edit.html =
edit.html =
<script language="javascript">
function InitializeIFrame() {
document.body.contentEditable = true;
}
</script>
<html>
<body onload="InitializeIFrame();">
</body>
</html>
推荐答案
我似乎回忆起当我遇到问题时尝试与iframe(同一个域等)进行通信。我发现的技巧是在框架内进行绑定并绑定到主窗口中的函数。像这样的东西(在edit.html中):
I seem to recall running into a problem when I was trying to communicate with an iframe (same domain etc). The trick I found is to do the binding inside the frame and bind to functions in the main window. Something like this (in edit.html):
<script>
$('body').bind("keyup keydown keypress", function(e) {
window.parent && window.parent.funcKey && window.parent.funcKey(e);
});
</script>
然后在主页中输入:
<script>
function funcKey(e) {
var code = e.keyCode || e.which;
alert(code);
return false;
}
</script>
我意识到这并不完全符合您尝试的方式,但效果相同已完成。根据我对javascript和iframe的理解,在实践中,与父母沟通比与iframe沟通更容易。如果你真的需要双向通信,你可以(在上面的例子中)使用函数funcKey()的返回值将数据传回iframe。
I realise this does not exactly fit into the way you were trying to do it, but the same effect is achieved. From what I understand of javascript and iframes, in practice it's easier to communicate with a parent than it is to communicate with an iframe. If you really need two-way communication you could (going on the example above) use the return value of the function funcKey() to pass data back into the iframe.
这篇关于jquery在iframe中侦听事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!