在javascript中修改图例

时间:2014-03-13 15:25:47

标签: javascript list

我基本上需要传说看起来像/说这样: 80+(或80%+) 75-80 70-75 65-70 60-65 55-50 < 50%

我按降序排列列表并且一切都很好,除非我不能使用小于符号才能正常工作。

代码是

var legend = L.control({position: 'bottomright'});

    legend.onAdd = function (map) {

        var div = L.DomUtil.create('div', 'info legend'),
            grades = [80, 75,70, 65, 60, 55, 50,],
            labels = [],
            from, to;

        for (var i =0; i < grades.length; i++) {
            from = grades[i-1];
            to = grades[i];

            labels.push(
                '<i style="background:' + getColor(to + 1) + '"></i> ' +
                to  + (from ?'&ndash;' + from : '+'));
        }

        div.innerHTML = labels.join('<br>');
        return div;
    };

    legend.addTo(map);

我需要做什么?

2 个答案:

答案 0 :(得分:0)

如果您只对为图例创建HTML标记感兴趣,并且图例数据永远不会更改,为什么不保持简单?

legend.onAdd = function (map) {

    var div = L.DomUtil.create('div', 'info legend');
    div.innerHTML = "<i style='background:green'>80+</i><br />"+
        "<i style='background:green'>75-80</i><br />"+
        "<i style='background:yellow'>70-75</i><br />"+
        "<i style='background:yellow'>65-70</i><br />"+
        "<i style='background:red'>60-65</i><br />"+
        "<i style='background:red'>55-60</i><br />"+
        "<i style='background:red'>50-55</i><br />"+
        "<i style='background:red'>&lt;50</i>";

    return div;
}

显然,您可能希望略微调整颜色,但这样更容易理解。没有理由不去制作少量的静态标记。

答案 1 :(得分:0)

所以我不知道L是什么,但我对你正在做的事情有了一般的了解。

类似

  

80 +

     

80 - 75

     

...

     

55 - 50

     

&LT; 50

问题是你需要检查3个场景。

  

仅限于(80 +)

     

往返(80-50)

     

仅来自(&lt; 50)

你所要做的就是改变这个

 for (var i =0; i < grades.length; i++) {
        from = grades[i-1];
        to = grades[i];

        labels.push(
            '<i style="background:' + getColor(to + 1) + '"></i> ' +
            to  + (from ?'&ndash;' + from : '+'));
    }

for (var i =0; i <= grades.length; i++) {
        /*don't cause an array out of bounds problem*/
        from = (i-1>-1)?grades[i-1]:0;
        to = (i < grades.length)?grades[i]:0;

        labels.push(
            '<i style="background:' + getColor(to + 1) + '"></i> ' +
             (/*Check to for a value*/to ? to : '&lt;') +
             ((/*Check both to and from for a value*/to&&from)?'&ndash;':'') + 
             (/*Check from for a value*/from  ? from + 
                 (/*check to for a value after knowing from has a value*/ to ? '': '%'): '%+'));
    }