2016-01-15 77 views
-1
index.html 
<script > 
function loadPage(){ 
    var xhttp,rtext,x; 
    xhttp=new XMLHttpRequest(); 
    xhttp.onreadystatechange=function(){ 
     if (xhttp.readyState == 4 && xhttp.status == 200) { 
      rtext=xhttp.responseText; 
      x = rtext.getElementById('bottom'); 
     } 
     document.getElementById("firstdiv").innerHTML=x; 
    }; 
    xhttp.open("GET","first.html",true); 
    xhttp.send(); 
} 

</script> 
    <body> 
    <div onClick="loadPage();">Home</div> 
    <div id="firstdiv"></div> 
    </body> 

first.html 

    <body> 
    <div id="bottom"> 
    <p>content 1</p> 
    </div> 
    <div id="bottom1"> 
    content 2 
    </div> 
    </body> 

我只需要從first.html加載「底部」div到我的索引頁面,僅使用javascript並面臨錯誤。使用Javascript從另一個頁面加載特定內容

的getElementById( '底部')沒有被定義屬性。

如何繼續?

回答

0

嘗試creating a new document與「first.html」的內容,然後查詢你想要的元素文件。

var doc = document.implementation.createHTMLDocument("Doc Title"); 
doc.body.outerHTML = rtext; 
var bottom = doc.getElementById('bottom'); 

未經測試,但可能是一個開始的地方。

0

JavaScript僅對當前頁面的元素進行操作。代碼執行時

rtext=xhttp.responseText; 
x = rtext.getElementById('bottom'); 

它期望在index.html上找到'底部'。當響應被加載到x中時,x包含first.html的文本,但它不被識別爲html,並且不能被解釋爲這樣。

我同意e-e的回答 - 這是一個開始的地方。

相關問題