2012-04-20 177 views
2

我在外部文件(的test.html)含量(#內容)在index.html的加載到另一個DIV(#result):jquery的簡單的Ajax負載

的test.html :

<div id="content">This text should not be loaded with its DIV. <strong> May contain other tags</strong></div> 

的jQuery:

$('#result').load('test.html #content'); 

index.html的結果,意想不到的:

<div id="result"><div id="content">This text should not be loaded with its DIV. <strong> May contain other tags</strong></div></div> 

index.html的結果,預計:

<div id="result">This text should not be loaded with its DIV. <strong> May contain other tags</strong></div> 

你如何加載它也可以包含其他標籤#內容的唯一實際內容/ HTML,而只是沒有它的包裝DIV(#content)? 原因是爲了避免不必要的瑣事,這些瑣事也可能與其他風格的DIV錯誤地發生衝突。

任何提示都非常感謝。謝謝

+1

您的標記似乎被打破(缺少結束「) – Shyju 2012-04-20 01:30:19

+0

謝謝,相應的更新 – swan 2012-04-20 01:32:39

+1

你不能做到這一點與'.load ()' – zerkms 2012-04-20 01:33:08

回答

1

這是一個想法。如果您使用臨時標籤作爲工作區會怎麼樣?

這個jQuery JavaScript的...

$('#workarea').load('test.html #content'); 

...可能會產生這樣的結果。請注意,工作區是隱藏:

<div id="result"></div> 
<div id="workarea" style="display: none"><div id="content>This text should not be loaded with its DIV</div></div> 

然後,你可以將它移動到這個結果......

$('#result').html($('#workarea').html()); 

應該產生這樣的結果。

<div id="result">This text should not be loaded with its DIV</div> 
<div id="workarea" style="display: none"><div id="content></div></div> 

編輯:

下面是完整的劇本都在同一個地方:

$('#workarea').load('test.html #content'); 
$('#result').html($('#workarea').html()); 

你會使用這兩條線,而不是你的一條線。如果我理解正確,它應該在上面的查詢中產生預期的結果。

+0

對不起,我沒有得到它是否意味着所有內聯文件?我使用exter的原因最終文件是因爲這些HTML太多而無法留在單個頁面中。請澄清。謝謝。 – swan 2012-04-20 01:45:51

+0

@swan能否澄清?你只需要將你的一個jquery行改爲我的兩行。我在解釋中將其分解,以逐步顯示它正在做什麼。 – digitaleagle 2012-04-20 02:49:08

+0

你的想法讓我有更好的解決方案。你的確更好,並且減少了大量的http請求。只加載一個HTML,然後通過加載的HTML中的ID進行分解,最後將每個ID插入父HTML小部分。輝煌。非常感謝。 – swan 2012-04-20 07:52:57

1

如果你能夠得到.load()的結果到var中。 你可以做到這一點。

var result = ... load line ... 
var outResult = $(result); 
// now strip the div out of outResult using jquery...... 
outResult = StripContentDiv(outResult); 
$('#result').html(outResult); 

對不起,因爲我不是一個jQuery的專家,我不能更具體。

+0

StripContentDiv是什麼功能,它是內置的jquery還是自定義?謝謝 – swan 2012-04-20 01:50:03

+0

您創建此函數。 – 2012-04-20 02:05:08

1

難道這就是你看

$(document).ready(function(){ 
    $('#result').load('test.html #content', function() { 
    $('#content', this).text; 
    }); 
    }); 

:P。的xD通過JNE

+0

謝謝,但不幸的是以下功能爲時已晚。 #內容已經加載了它的DIV。 – swan 2012-04-20 02:14:03