我试图用jquery迭代xml并将其发布在html上.由于某种原因,作者中的每个函数都附加了重复项.例如,我将获得James McgovernPer BothnerKurt BothernerKurt CagleJames Linn Valiyanathan Nagarjan,James McgovernPer BothnerKurt BothernerKurt CagleJames Linn Valiyanathan Nagarjan.我想知道如何解决这个问题?谢谢!
<book category="web">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
$(document).ready(function() {
$.ajax({
url: "books.xml",
dataType: "xml",
success: function(data) {
$(data).find('book').each(function(){
var category = $(this).attr('category');
var title = $(this).find('title').text();
var year = $(this).find('year').text();
var price = $(this).find('price').text();
var author = $(this).find('author').text();
$(this).find('author').each(function(){
author += $(this).text();
author += ',';
});
var r = '<tr>';
r += '<td>' + title + '</td>';
r += '<td>' + author + '</td>';
r += '<td>' + year + '</td>';
r += '<td>' + price + '</td>';
r += '<td>' + category + '</td>';
$('table').append(r);
});
},
error: function() { alert("error loading!"); }
});
});
解决方法:
你首先设置auther到$(this).find(‘author’).text(),然后在每个中添加行.这导致列表重复.
您应该只使用var author =”替换第一个赋值.