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中的代码出了什么问题?
答案 0 :(得分:1)
for循环中的element
不是jQuery包装对象,这就是错误的原因。
您可能必须使用
var $car = $(element);