我有这样的XML:

<?xml version="1.0"?>
<service>
    <name>My Element</name>
    <header>My Header</header>
    <sections>
        <section>
            <!-- Optional -->
            <subheader>Subheader 1</subheader>
            <description>Here goes the content</description>
        </section>
        <!-- Optional -->
        <section>
            <subheader>Subheader 2</subheader>
            <description>Here goes the content</description>
        </section>
    </sections>
</service>


我正在尝试从每个部分读取“ subheader”和“ description”元素的值。但是,我无法检索这些元素的值。这是我的代码:

function getDescription(descriptor_url) {
        var descriptor_object = $.get(descriptor_url, function(descriptor_data, descriptor_status, descriptor_response) {
            $(descriptor_response.responseXML).each(function () {
                //this works fine
                var header = $(this).find('header').text();
            });
            $(descriptor_response.responseXML).find('sections').each(function() {
                // here is where the issue is
                $(this).find('section').each(function() {
                    var subheader = $(this).find('subheader').text;
                    // Included a screenshot of this alert here
                    alert(subheader);
                })
            })
        })
        .fail(function() {
           response.value = "Something went wrong with the request.\n\nReason: " + descriptor_object.statusText;
        })
    }


我以为$(this)对于$ .each循环是本地的,但是看起来我错了。有人可以帮忙吗?

谢谢!

最佳答案

请注意,在原始帖子中,var subheader = $(this).find('subheader').text;之后似乎没有()

尝试

    $(descriptor_response.responseXML).each(function () {
            //this works fine
            var header = $(this).find('header').text();
            var subheaders = $(this).find("sections section subheader").text();
            var descriptions = $(this).find("sections section description").text();
            alert(header + "\n" + subheaders + "\n" + descriptions);
        });


jsfiddle http://jsfiddle.net/guest271314/hv46r/

09-12 10:45