2014-06-16 47 views
0

我想知道爲什麼我可以使用.load到的信息非常具體的位裝載到一個頁面,但後來當我嘗試讀回我剛回到nulljQuery的.load工作,但不可讀

這個載入信息是我使用加載的信息

$(function(){ 
    $('#code').load('stuff.html #specificstuff'); 
}); 

該位jQuery和這是我使用重複什麼代碼#code

var content = document.getElementById('#code'); 
document.write(content); 

但這個程序運行時,我剛剛回到null

+0

您正試圖在不同的域上加載的頁面? –

+0

@MarioJVargas nope同域,並且.load函數確實有效,但不會被讀回 – user3743076

+0

'#code'是什麼類型的元素?而stuff.html頁面是否包含ID爲'specificstuff'的元素? –

回答

2
document.getElementById('#code'); 

應該

document.getElementById('code'); 

話雖這麼說......我不知道爲什麼你在第一時間使用document.write

而且你需要等待加載完成,所以它會更有意義的事:

$('#code').load('stuff.html #specificstuff', function(){ 
    var content = document.getElementById('code').html(); 
    document.write(content); 
}); 
0

$.load()是asyncronous,所以你的代碼:

var content = document.getElementById('#code'); 
document.write(content); 

被執行之前實際的內容被加載。

把它放在這樣一個回調函數:

$(function(){ 
    $('#code').load('stuff.html #specificstuff', function(){ 
     var content = document.getElementById('code'); 
     document.write(content); 
    }); 
}); 

所以它被執行後的內容已經完成加載。

這就是說,document.write(content);在這種情況下是無用的,因爲$('#code').load()替換元件的與id="code"與元件文件stuff.html#specificstuff的內容的內容。

+0

感謝您的回答,但我已經完全按照您的說法使用,但發現我得到的僅僅是[對象HTMLSpanElement] – user3743076

+0

@ user3743076,這是因爲'document.getElementById('代碼')'返回DOM節點。可能'document.write(content.innerHTML)是你想要的。 –