2015-10-14 58 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>"); 
}