-->

Using jQuery to update content within an iFrame li

2019-09-19 07:39发布

问题:

I'm using an iframe to display a website next to a form. I want to update certain content within that iframe live based upon the value of the various input fields.

This is what I'm trying to do (working outside of an iframe): http://jsfiddle.net/YkKUS/

The textarea will be outside of the iframe and the content that'll be updated will be inside the iframe.

Here is my code adapted to work with my iframe:

            $('.liveDemoFrame').load( function(){   // load the iframe          
                $(this.contentDocument).find('h1').html($('textarea').val());                   
                $('textarea').keyup(function() {
                    $(this.contentDocument).find('h1').html($(this).val()); // this line is screwing something up?!?
                });    
            });

The 5th line is causing me some problems. The iframe DOES actually update successfully with the content of my textarea but only when I refresh the page. It's not updating it live & on-the-fly which is the only reason I'm doing this!

Thanks!

回答1:

I did this in the parent page and it seemed to work:

$(document).ready(function(){
    $('#textarea').bind('keyup', function() {
        var iframedoc = $('#iframe').get(0).contentDocument;
        $(iframedoc).find('h1').html($(this).val());
    });
});


回答2:

There might be some kinks with jQuery, or you might be doing it incorrectly. Either way, it could be easiest to actually run half of your code within the iframe; then you can call iframe.contentWindow.getHtml(), or iframe.contentWindow.setHtml(), if you can. Also IIRC, the contentDocument was not standard either; some browsers require contentWindow.document or similar.

However, the main culprit would be this:

$('.liveDemoFrame').load( function(){
    $(this.contentDocument).find('h1').html($('textarea').val());
    $('textarea').keyup(function() {
         // here this refers to textarea dom element, not iframe
         $(this.contentDocument).find('h1').html($(this).val()); 
    });    
});

Fix could be like

$('.liveDemoFrame').load( function(){
    var iframeDocument = $(this.contentDocument);
    iframeDocument.find('h1').html($('textarea').val());
    $('textarea').keyup(function() {
         // here this refers to textarea dom element, not iframe
         iframeDocument.find('h1').html($(this).val()); 
    });    
});


回答3:

You can't do stuff in the iframe from outside of it, that would be a massive security hole