Using jQuery to update content within an iFrame li

2019-09-19 07:43发布

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!

3条回答
家丑人穷心不美
2楼-- · 2019-09-19 07:56

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楼-- · 2019-09-19 07:58

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

查看更多
混吃等死
4楼-- · 2019-09-19 08:08

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());
    });
});
查看更多
登录 后发表回答