使用jquery ajax与xml文件时出现错误消息

时间:2013-07-16 03:19:47

标签: jquery ajax

data.xml中

<?xml version="1.0" encoding="utf-8"?>
<cars>
    <car company="TOYOTA">
        <product>Prius</product>    
        <colors>
            <color>white pearl</color>
            <color>Red Methalic</color>         
            <color>Silver Methalic</color>                      
        </colors>
        <type>Gen-3</type>
    </car>
    <car company="TOYOTA">
        <product>New Fortuner</product> 
        <colors>
            <color>super white</color>
            <color>Black</color>            
            <color>Silver</color>                       
        </colors>
        <type>Fortuner TRD Sportivo Limited Edition</type>
    </car>  
</cars>

page.html中

<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">
</script>
    <script type="text/javascript">
    $(document).ready(function() {
        $('#car').click(function() {
            $.get('data.xml',function(data){
                $('#content').empty();
                $(data).find('car').each(function(index, element){
                    var $car = element;
                    var html = '<div class="data">';                      
                    html += '<h3>' + $car.attr('company') + '</h3>';
                    html += '<div class="product">' + $car.find('product').text() + '</div>';                   
                    html += '<div class="type">' + $car.find('type').text() + '</div>';
                    $('#content').append(html);
                });                        
            });
            return false;
        });
    });
    </script>
</head>
<body>

<a href="#" id="car">Car</a>
<div id="content">
</div>
</body>
</html>

当我运行page.html并点击链接时:Car,在chrome,console中,它显示:

Uncaught TypeError: Object #<Element> has no method 'attr' 

那么page.html中的代码出了什么问题?

1 个答案:

答案 0 :(得分:1)

for循环中的element不是jQuery包装对象,这就是错误的原因。

您可能必须使用

var $car = $(element);