如何无需XSLT模板按LastName对XML feed进行字母排序
按LastName对XML中的艺人进行字母排序的解决方案
嘿,我注意到你当前的代码只是直接遍历XML里的artist元素并生成HTML,没有做排序处理。要实现按LastName字母排序其实不难,咱们可以先把所有艺人的数据提取出来存成数组,排好序后再渲染,这样就能达到你的需求了。
具体修改思路:
- 先创建一个数组来存储每个艺人的完整数据(姓名、头像链接、页面链接等)
- 遍历XML时,把每个艺人的信息以对象形式存入数组
- 对数组按照
LastName进行不区分大小写的字母排序 - 最后遍历排序后的数组,批量生成HTML插入页面
修改后的完整代码:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> $(document).ready(function(){ $.ajax({ type: "GET", url: "https://cors-anywhere.herokuapp.com/https://showcast.com.au/showcast/webservice/actors.aspx?agencyId=&Password=", dataType: "xml", success: parseXml }); }); function parseXml(xml){ // 初始化数组存储艺人数据 const artists = []; $(xml).find("artist").each(function(){ const firstName = $(this).find("FirstName").text(); const lastName = $(this).find("LastName").text(); const fullName = `${firstName} ${lastName}`; let profilePic = ''; // 查找默认头像 $(this).find("Photos SmallPhotos Photo").each(function(){ if ($(this).find("IsDefault").text() === "True") { profilePic = $(this).find("Url").text(); return false; // 找到默认头像就停止遍历 } }); const profileLink = $(this).find("URLlink").text(); // 将当前艺人数据存入数组 artists.push({ lastName, fullName, profilePic, profileLink }); }); // 按LastName字母排序(不区分大小写) artists.sort((a, b) => { const nameA = a.lastName.toLowerCase(); const nameB = b.lastName.toLowerCase(); return nameA.localeCompare(nameB); // 用localeCompare更简洁,还能处理特殊字符排序 }); // 批量生成HTML,减少DOM操作次数 let htmlOutput = ''; artists.forEach(artist => { htmlOutput += ` <div class="nxitem"> <a href="${artist.profileLink}" class="nxclearfix"> <div class="nxwrap"> <div class="nximgwrap"> <img src="${artist.profilePic}"> </div> </div> <br/> <span class="nxname">${artist.fullName}</span> </a> </div> `; }); $("#nxdisplay").append(htmlOutput); } </script>
关键优化点说明:
- 排序逻辑:用
localeCompare替代手动字符比较,代码更简洁,还能更好地处理带特殊字符的姓氏排序 - DOM操作优化:先拼接好所有HTML字符串再一次性插入页面,比每次调用
append更高效,减少页面不必要的重绘 - 代码可读性:用了模板字符串让HTML拼接更直观,变量名也更语义化,后续维护起来更方便
另外,关于你提到的运行报错,常见的可能原因有这几个:
- 跨域问题:cors-anywhere的免费服务偶尔会不稳定,如果长期使用建议自己搭建一个简单的CORS代理
- XML节点缺失:如果返回的XML里某个艺人没有
FirstName或LastName,会导致空字符串,你可以给这些值加个默认值,比如$(this).find("FirstName").text() || 'Unknown' - jQuery版本过旧:1.11版本是比较老的了,如果可以的话升级到较新的稳定版,能避免一些已知的兼容性问题
内容的提问来源于stack exchange,提问作者Nick Barraclough
相关产品推荐
相关产品推荐

