0

数据.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 中,控制台时,它显示:

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

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

4

1 回答 1

1

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

您可能必须使用

var $car = $(element);
于 2013-07-16T03:20:35.247 回答