簡體   English   中英

如何使用jQuery從Ajax提取的內容中提取HTML

[英]How to Extract HTML from Content Fetched with Ajax using jQuery

我有一個頁面,其中有一些Option元素,其Value指向外部頁面。 我的目的是使用Ajax提取所選Option的Value並使用它從外部頁面加載內容。 例如,當用戶選擇“排球”時,我將獲得“ volleyball.html”值,使用Ajax檢索該頁面並將其#catalog內容加載到當前頁面中。 這是我的代碼:

$("select").change(function(){
var selectedURL=$("option:selected",this).val();
if(selectedURL!=="Select One"){
    $("#center").html("<p class='processing'></p>");    
    $.get(selectedURL,function(data){
    var extractedContent=$("#catalog",data);
    console.log(extractedContent); //Firebug says extractedContent is '[]'
    $("#center").html(extractedContent); //Nothing is inserted inside div#content
    },"html");
}

我不太擅長jQuery,並且從上面的幾篇文章中得到了一些混合和匹配的代碼,以得出上面的內容。 現在,我不確定出了什么問題,但是沒有加載任何內容-應該保存已提取內容的#center div塊為空。

有人可以幫我找出上面我的代碼有什么問題嗎? 提前謝謝了。

load()方法非常適合:

$('select').change(function () {
    var selectedURL = $('option:selected', this).val();

    if (selectedURL !== 'Select One') {
        $('#center').html('<p class="processing"></p>').load(selectedURL + ' #catalog');
    }
});

它可以采取只有一個URL, 它可以采取URL后跟一個選擇器,其將僅在匹配元素(的內容裝載#catalog )到它被稱為上(元件#center )。

$("select").change(function(){
    var selectedURL=$("option:selected",this).val();
    if(selectedURL!=="Select One"){
        $("#center").html("<p class='processing'></p>");    
        $.get(selectedURL,function(data){
            $("#center").html($(data).find("#catalog"));
        },"html");
    }
});

不能那樣使用$('#catalog', data) 要提取內容,您可以創建一個jQuery對象,並分配返回的HTML,然后從那里提取:

var extractedContent = $('<div />').html(data).find('#catalog').html();
console.log(extractedContent);
$("#center").html(extractedContent); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM