2013-08-26 35 views
1
DOM變更後的.html失敗

我使用jQuery使用下面的代碼來改變一個iframe的網頁上的內容:Jquery.text()和I幀

<!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> 

我可以看到的變化實際的網頁,但更改不會出現在日誌中。我嘗試使用.html()函數,但我有同樣的問題。我創建了一個jsfiddle:http://jsfiddle.net/AbE89/

我在stackoverflow上發現了類似的問題,但這主要是一個過時的瀏覽器問題,我正在使用最新的chrome。我也嘗試過最新版本的Firefox,但仍然沒有運氣。有沒有人遇到同樣的問題?

+0

嘗試'的console.log( $('#result iframe')。contents()。find('html')。html())' –

回答

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) 
}); 

演示:Fiddle

如果你想在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) 
}); 

演示:Fiddle