2011-04-10 77 views
9

我的問題很簡單,我怎麼可以檢索特定的div使用jQuery阿賈克斯COMANDjQuery的AJAX負荷一定的div

$.ajax({ 
     url: "test.html", 
     success: function(){ 
      $(this).addClass("done"); 
     } 
    }); 

像負載

$('#targetDiv').load('http://localhost/test.html #sourceDiv'); 
+0

有沒有理由不簡單地使用'load()'? – 2011-04-10 18:36:38

回答

17

如果DIV是Ajax響應的一部分:

$.ajax({ 
    url: 'test.html', 
    dataType: 'html', 
    success: function(html) { 
     var div = $('#sourceDiv', $(html)).addClass('done'); 
     $('#targetDiv').html(div); 
    } 
}); 
+0

謝謝,但有什麼不對,這完全沒有運行,當加載完成我的目標div是空的 – Yovo 2011-04-10 13:03:57

+0

@Yovo,返回的HTML是否包含帶'id =「sourceDiv」'的div?嘗試用FireBug查看服務器響應,並在成功回調中記錄div變量。 – 2011-04-10 13:04:46

+0

實際上螢火蟲顯示它被加載。我嘗試加載整個文件,一切正常,但當我選擇特定的DIV瀏覽器隱藏它。 – Yovo 2011-04-10 14:52:17

6

這是一個略有不同的考慮。此外,您的目標股利可能隱藏默認,所以我已經添加了淡入影響來顯示它。如果你的html將要改變,那麼你可能想添加一個緩存:false。

$.ajax({ 
    url: "html.htm", 
    type: "GET", 
    dataType: "html", 
    success: function (res) { 
     $("#targetDiv").html($(res).find("#sourceDiv") 
            .addClass('done')) 
        .fadeIn('slow'); 
    } 
}); 

如果你有興趣,你可以看看jQuery的如何做負載方法這裏jQuery Source Viewer

2

這裏是我在我的網站的導航用一個例子。

<ul id="nav">   
    <li><a name="portfolio" href="portfolio.php" class="ajax_nav">PORTFOLIO</a></li> 
    <li><a name="biography" href="biography.php" class="ajax_nav">BIOGRAPHY</a></li> 
</ul> 

對於JavaScript,你可以試試這個。

var hash = window.location.hash.substr(1); 
var hash2 = window.location.hash.substr(1); 

// Menu items to lower main content 
var href = $('.ajax_nav').each(function(){ 
    var href = $(this).attr('href'); 
    if(hash==href.substr(0,href.length-4)){ 
     var toLoad = hash+'.html #ajax_content'; 
     $('#ajax_content').load(toLoad) 
    }           
}); 

// For inner overlay of featured content. 
var href2 = $('.feat_item_link').each(function(){ 
    var href2 = $(this).attr('href'); 
    if(hash2==href2.substr(0,href.length-4)){ 
     var toLoadFeatured = hash2+'.html #ajax_featured_content'; 
     $('#ajax_featured_content').load(toLoadFeatured); 
    }           
}); 

// For Bottom Navigation 
$('#nav li a').click(function(){ 

    var toLoad = $(this).attr('href')+' #ajax_content'; 
    $('#content').hide('fast',loadContent); 
    $('#load').remove(); 
    $('#wrapper').append('<span id="load">LOADING...</span>'); 
    $('#load').fadeIn('normal'); 

    window.location.hash = $(this).attr('href').substr(0,$(this).attr('href')); 
    function loadContent() { 
     $('#content').delay(1000).load(toLoad,'',showNewContent()); 
    } 
    function showNewContent() { 
     $('#content').show('normal',hideLoader()); 
    } 
    function hideLoader() { 
     $('#load').delay(1000).fadeOut('normal'); 
    } 
    return false; 
}); 

#load的id只是在CSS中使用了一個動畫gif。

將JavaScript放在$(document).ready()中,並且應該全部設置。