2017-02-17 12 views
0

我有一个地图,其features根据地图范围而变化。功能renderListings为每个功能创建一个元素item,然后在每次地图更改时将所有项目添加到listingEl。到目前为止,这工作正常。附加子项和排序动态列表

item的每个iteminnerHTML基于功能的属性 - prop.code,这是一个文本字符串。此时函数以无序的方式追加项目,而不是按字母顺序。

我已经尝试将.sort()添加到listingEl.appendChild(item).sort(),但只有一个项目出现在列表中,其他所有项目都消失。

怎么会按字母顺序追加儿童的功能属性prop.code在JavaScript中?

var listingEl = document.getElementById('feature-listing'); 


function renderListings(features) { 
    // Clear any existing listings 
    listingEl.innerHTML = ''; 
    if (features.length) { 
     features.forEach(function(feature) { 
      var prop = feature.properties; 
      var item = document.createElement('a'); 
      item.target = '_blank'; 
      item.innerHTML = '<div style ="display:inline;"> ' + prop.code + ' </div>' 


      listingEl.appendChild(item); 

     }); 

回答

0

只需在将功能添加到列表中之前对其进行排序即可。

var listingEl = document.getElementById('feature-listing'); 

function renderListingsSorted(features) { 
    var sortedFeatures = sortFeaturesByCode(features); 
    renderListings(sortedFeatures); 
} 

function sortFeaturesByCode(features) { 
    return features.sort(function(f1, f2){ 
     var code1 = f1.properties.code; 
     var code2 = f2.properties.code; 
     return code1.localeCompare(code2); 
    }); 
} 

function renderListings(features) { 
    // ... 
} 
+0

这不起作用,因为'features'即进入'renderListings()'不排序 –

+0

你的意思是'sortFeaturesByCode'功能并不功能实际上排序? – abl

+0

没错,列表并没有被排序,因为一切都应该在'renderListings()'函数中,如果可能的话 –