2011-10-13 27 views
5

Tôi đang cố gắng tải nội dung từ một div trang khác vào một div trang khác.Cách tải văn bản thuần tuý vào div từ một trang khác

gì tôi đã có:

jQuery:

$('#news_date-1').load('test.php .news_date-1'); 

test.php

<div class="news_date-1">20-11-2009</div> 

Destination.html

<div id="news_date-1"></div> 

Kết quả tôi nhận được =

<div id="news_date-1"><div class="news_date-1">20-11-2009</div></div> 

Kết quả tôi muốn =

<div id="news_date-1">20-11-2009</div> 

Ai có thể giúp đỡ?

Trả lời

3

Bạn có thể thử gọi unwrap() vào nó trong callback.

$('#news_date-1').load('test.php .news_date-1', function() { 
    $(this) //will refer to #news_date-1 
     .find('.news_date-1') //find the inserted div inside 
     .contents() //find all its contents 
     .unwrap(); //unwrap the contents, thus removing the unneeded div 
}); 

Đây không phải là giải pháp đẹp nhất, bởi vì .load() đã chèn nó vào DOM, và sau đó bạn làm xáo trộn DOM một lần nữa, mà phải được giảm thiểu.

Một cách khác tôi thấy đang sử dụng $.get() thay vì:

$.get('test.php', function(receivedHtml) { 
    //getting only the parts we need 
    var neededHtml = $(receivedHtml).find('.news_date-1').html(); 
    //adding it to DOM 
    $('#news_date-1').append(neededHtml); 
}); 
0

Hãy thử điều này:

$.get('test.php', function(data) { 
    $('#news_date-1').append($(data).find('.news_date-1')); 
}); 
+0

làm cho không có sự khác biệt – ronni

Các vấn đề liên quan