即使某些属性正在运行,XML中的未定义语句也是如此

时间:2014-12-19 09:53:35

标签: jquery xml

我收到的是#34; Undefined"我的xml的某些部分的声明有谁知道为什么?它显示的是图片和标题,但文本只显示为未定义

这是xml:

<Parent>
  <Child
     land="Germany"
     headline="Beer"
     src="images/beer.png"
     text="Das klassische Schwarzbier hat seinen Ursprung in Thüringen"
     ingredients="Water, Hops"
  />
</Parent>

和JQuery

$(function () {

        $(window).bind('load', function () {
            $.ajax({
                type: "GET",
                url: "test.xml",
                async: false,
                dataType: "xml",
                success: Template
            });
        });

        function Template(xml) {

            $(xml).find('Parent').each(function () {

             /* BODY IS CREATED HERE */
               $(xml).find('Child').each(function () {
                    $('<div id="inline-' + ($(this).attr('headline')) + '" class=sensebox-container"><div class="sensebox-img"><img src="' +($(this).attr('src')) +'">' +
                    '<h3>' + ($(this ).attr('headline')) + '</h3><p>' + ($(this ).attr('text')) + '</p>').appendTo(body);
})
})

1 个答案:

答案 0 :(得分:1)

首先,您将load事件附加到DOMReady事件下的窗口。这是毫无意义的,因为窗口加载事件在DOMReady事件之前触发,所以你也可以在那时触发AJAX请求。

您的XML解析问题是Parent元素是根,因此您需要使用filter而不是find来访问它。最后,在appendTo中,除非body是一个包含jQuery对象的变量,否则应引用它,以便选择body元素。以下是完整的示例:

$(function () {
    $.ajax({
        type: "GET",
        url: "test.xml",
        dataType: "xml",
        success: Template
    });

    function Template(xml) {
        $(xml).filter('Parent').each(function () {
            $(xml).find('Child').each(function () {
                $('<div id="inline-' + $(this).attr('headline') + '" class=sensebox-container"><div class="sensebox-img"><img src="' + $(this).attr('src') +'"><h3>' + $(this ).attr('headline') + '</h3><p>' + $(this ).attr('text') + '</p>').appendTo('body');
            })
        })
    }
});

Example fiddle

另请注意,您的HTML不包含您打开的div元素的结束标记,我删除了async: false属性,因为如果您不打算使用AJAX,则不应该这样做。重新制作是同步的。