2015-04-22 292 views
1

我有兩個iframe,它們都包含一個帶有文本區域的表單。如何在獨立的iframe中同步兩個文本區域?

我的目標是同步兩個文本區域,以便在另一個文本區域中再現用戶輸入的內容。我如何跨兩個(或更多)獨立的iframe做到這一點?

主文檔:I幀的

<script> 
$("iframe").ready(function(){ 
    $(".editor").keyup(function(){ 
     $(".editor").val($(this).val()); 
    }); 
}); 
</script> 

<iframe src="/editor.php?mode=post&f=1" class="iframe-editor"></iframe> 
<iframe src="/editor.php?mode=post&f=2" class="iframe-editor"></iframe> 

內容:

<fieldset class="fields1"> 

    <textarea name="message" id="message" class="editor">{MESSAGE}</textarea> 

</fieldset> 

截至目前,如果文本區設置在主文檔中我的jQuery腳本纔有效。

+0

我敢肯定你不能有JavaScript的影響出於安全原因的內部(或外部)iframe中。 – DLeh

+0

如果iframe屬於不同的域,我認爲這是真的。在我的情況下,主文檔和iframe都在同一個域中。 –

+0

如果我錯了,我不能確定它可以完成(我希望^^)告訴我,因爲我也有興趣 – MacKentoch

回答

1

您設置的方式不起作用,因爲「.editor」屬於另一個DOM。但是,您可以使用"contentWindow" property of the IFRAME element訪問該DOM。

您還可以將myIframe.contentWindow.document作爲context傳遞給jquery,以便jquery在那裏搜索。

http://jsfiddle.net/cbv0xfq2/

$('.iframe-editor').each(function() { 
    var frame = this; 

    $(frame.contentWindow.document.body).on('input', '.editor', function() { 
    var textarea = $(this); 
    $(".iframe-editor").not(frame).each(function() { 
     $('.editor', this.contentWindow.document).val(textarea.val()); 
    }); 
    }); 
}) 
+0

也許我失去了一些明顯的東西,但它似乎並沒有在我的最後。它應該在第一行有'.iframe-editor',並且在第六行有'.containerFrame'? –

+0

nope,應該是'.iframe-editor',你是對的。 – Roman