首页 > 解决方案 > 如何按元素内容过滤解析的 XML 数据 [jQuery]

问题描述

所以我有一个 xml 房屋属性提要 [在 WordPress 网站上] 目前非常简单,它只是收集我想要显示的字段并将其显示为列表 [非常正常的东西] 但我现在需要能够制作两个列表,一个只显示已售出的房产,一个不显示已售出的房产。目前我的代码如下:

jQuery(function( $ ){

$(document).ready(function()
{
    $.ajax({
        type: "GET",
        url: "/properties2.xml",
        dataType: "xml",
        success: parseXml
    });
});

function parseXml(xml)
{
    $("#xmlmain").html("<div id='content' data-role='listview' data-inset='true'></div>");
    $(xml).find("property").each(function() {
        $("#content").append("<div class='xmlwrapper'><div class='xmlleft'><img src='"+$(this).find('[name="Photo 1"]').text()+"'/></div><div class='xmlright'><h2>"+$(this).find("advert_heading").text()+"</h2><p class='price'>"+$(this).find
        ("price_text").text()+"</p><p class='priority'>"+$(this).find("priority").text()+"</p><p>"+$(this).find("main_advert").text()+"</p><a href='"+$(this).find("web_link").text()+"' target='_blank'>VIEW > </a></div></div>");
    });
}
});

我是 Javascript 和 Jquery 的新手,所以我真的不知道如何过滤列表以排除已售出的属性,只包括已售出的属性。我如何调整/过滤它以获得所需的结果?我尝试使用 filter(); 功能,但它只是一直停止显示提要。

这是我试图合并/使用的片段/示例:

var getTextNodesIn = function(el) {
return $(el).find(":not(iframe)").addBack().contents().filter(function() {
    return this.nodeType == 3;
    });
};

getTextNodesIn(el);

我需要使用的数据在下面显示的优先级字段中。以下是 xml 提要的摘录:

<properties>
<property reference="MR139">
    <instructedDate>06/08/2018 17:07:05</instructedDate>
    <price_text>£600,000</price_text>
    <numeric_price>600000.0000</numeric_price>

    <priority>On Market</priority>

    <advert_heading>house for sale</advert_heading>
    <main_advert>some text about the property</main_advert>
    <web_link>www.example.com</web_link>
    <property_style>Detached</property_style>
    <property_reference>111111</property_reference>
    <newHome>NO</newHome>
    <noChain>NO</noChain>
    <furnished>Unknown</furnished>
    <currency>GBP</currency>
    <featuredProperty>NO</featuredProperty>
    <pictures>
        <picture name="Photo 1" lastchanged="2018-08-06T15:44:48.5800534Z">
            <filename>example.jpg</filename>
        </picture>
    </pictures>
</property>
</properties>

[已售物业的优先字段中的文本将是“已售”或“已售 STC”,如果这有所不同的话。]

任何帮助将不胜感激,即使它只是指向我可以使用的与我的问题相关的资源。我的搜索似乎出现了不相关的信息,这可能是由于我不正确了解术语而导致措辞错误。

标签: javascriptjqueryhtmlxmlxml-parsing

解决方案


您可以使用如下方法检查方法priority中的值。eachstartsWith

$(xml).find("property").each(function() {
    var priority = $(this).find("priority").text();

    if(priority.startsWith('Sold')) {
        //for sold properties
    } else {
        //for unsold properties
    }
});

推荐阅读