1

次のコードを使用して、Jquery を使用して Web ページ上の iframe のコンテンツを変更しています。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script type="text/javascript" src="jquery.min.js"> </script>
</head>

<body>
<script type="text/javascript">
$(document).ready(function(){
    var html1 = $('#result iframe').text();
    console.log('Before');
    console.log(html1)
    $('#result iframe').contents().find('body').append('<p>hello</p>');
    var html2 = $('#result iframe').text();
    console.log('After');
    console.log(html2)
});

 </script>
    <div id="result">
        <iframe id="result">
            <html>
                <head>
                </head>
                <body>
                </body>
            </html>
        </iframe>
    </div>


</body>
</html>

実際の Web ページでは変更を確認できますが、変更はログには表示されません。.html() 関数を使用してみましたが、同じ問題があります。jsfiddle を作成しました: http://jsfiddle.net/AbE89/

stackoverflow で同様の問題を見つけましたが、これは主に古いブラウザーの問題であり、最新のクロムを使用しています。最新バージョンの Firefox でも試してみましたが、まだうまくいきません。誰かが同じ問題に遭遇しましたか?

4

1 に答える 1

0

試す

$(document).ready(function(){
    var html1 = $('#result iframe').contents().find('html').html();
    console.log('Before');
    console.log(html1)
    $('#result iframe').contents().find('body').append('<p>hello</p>');
    var html2 = $('#result iframe').contents().find('html').html();
    console.log('After');
    console.log(html2)
});

デモ:フィドル

<html>HTMLに要素も含めたい場合は、

$(document).ready(function(){
    var html1 = $('#result iframe').contents().find('html').get(0).outerHTML;
    console.log('Before');
    console.log(html1)
    $('#result iframe').contents().find('body').append('<p>hello</p>');
    var html2 = $('#result iframe').contents().find('html').get(0).outerHTML;
    console.log('After');
    console.log(html2)
});

デモ:フィドル

于 2013-08-26T03:10:39.120 に答える