2015-10-14 56 views
1

我想让这段代码根据标题进行排序,但用超链接显示标题。到目前为止,代码正确排序,但超链接不被正确的标题显示。它似乎是按照标题按字母顺序排列列表链接,然后按标题顺序链接子网站。排序数组超链接

我想:
第一子网站(www.test.com/firstsubsite)
谷歌(www.google.com)// < - 在列表
最后子网站(www.test.com/lastSubsite )
雅虎(www.yahoo.com)// < - 在列表

目前我得到:
第一子网站(www.google.com)// < -In名单
谷歌(www.yahoo.com)// < - 在列表
最后的子网站(www.test.com/firstsubsite)
雅虎(www.test.com/lastSubsite)

function GetItems() { 
 
    var names = []; 
 
    var link = []; 
 
    $().SPServices({ 
 
     operation: "GetListItems", 
 
     async: true, 
 
     listName: "GatheredSites", 
 
     CAMLViewFields: "<ViewFields><FieldRef Name='Title' /><FieldRef Name='Link_x0020_Url' /></ViewFields>", 
 
     completefunc: function(xData, Status) { 
 
      $(xData.responseXML).SPFilterNode("z:row").each(function() { 
 
       var url = $(this).attr("ows_Link_x0020_Url").split(",")[0]; 
 
       var name = ($(this).attr("ows_Title")); 
 
       names.push(name); 
 
       link.push(url); 
 
      }); 
 
      $().SPServices({ 
 
       operation: "GetWebCollection", 
 
       webURL: "*url*", 
 
       async: true, 
 
       completefunc: function(xData, Status) { 
 
        $(xData.responseXML).find("Webs > Web").each(function() { 
 
         var $node = $(this); 
 
         names.push($node.attr("Title")); 
 
         link.push($node.attr("Url")); 
 
        }); 
 
        names.sort(); 
 
        var output = $("#divDisplay"); 
 
        for (var i = 0, len = names.length; i < len; i++) { 
 
         output.append("<li><a href='" + link[i] + "'>" + names[i] + "</li>"); 
 
        } 
 
       } 
 
      }); 
 
     } 
 
    }); 
 
}

回答

2

names数组排序后,您无法匹配links数组中的对应索引。

您可以创建一个对象,该对象在xml的每次迭代中都有名称和链接,并将该对象推送到一个数组中。

然后通过名称属性的对象的单个阵列排序

$(xData.responseXML).find("Webs > Web").each(function() { 
    var $node = $(this); 
    // single object to store all needed properties from xml 
    var item = { 
     name: $node.attr("Title"), 
     link: $node.attr("Url") 
    } 
    // push object to array 
    names.push(item); 
    // link.push($node.attr("Url")); - remove links array, no longer needed 
}); 
// sort array by name property 
names.sort(function (a, b) { 
    return a.name > b.name 
}); 
var output = $("#divDisplay"); 

for (var i = 0, len = names.length; i < len; i++) { 
    // note properties used for link and name 
    output.append("<li><a href='" + names[i].link + "'>" + names[i].name + "</li>"); 
}