如何使用 jQuery 从使用 Ajax 获取的内容中提取 HTML

How to Extract HTML from Content Fetched with Ajax using jQuery

本文关键字:HTML 提取 获取 Ajax jQuery 何使用      更新时间:2023-09-26

>我有一个页面,其中有几个选项元素,其值指向外部页面。我的目标是使用Ajax提取所选选项的值并使用它来从外部页面加载内容。例如,当用户选择排球时,我将获得"排球.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,并且从这里的一些帖子中获得了混合和匹配的代码,以得出上面的内容。现在我不确定出了什么问题,但没有加载任何内容 - 应该保存提取内容的 #centerdiv 块是空的。

有人可以帮我发现上面的代码有什么问题吗?提前非常感谢。

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)中。

你不能像那样使用$('#catalog', data)。要提取内容,您可以创建一个 jQuery 对象,并分配返回的 HTML,然后从那里提取:

var extractedContent = $('<div />').html(data).find('#catalog').html();
console.log(extractedContent);
$("#center").html(extractedContent); 
$("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");
    }
});