在每个循环javascript / jquery中访问变量

时间:2015-04-15 10:21:56

标签: javascript jquery google-maps

我很欣赏这是一个常见问题,但我是JavaScript / JQuery的新手,我无法解决这个问题。我在.each循环中在谷歌地图中创建一个新的多边形,而我正确地能够访问我的多边形数据,因为我迭代模型,我得到相同的颜色值。多边形颜色始终为绿色。

这是预期的,因为我知道JavaScript中的作用域/循环/闭包存在问题,但我不明白为什么我在这里得到一个而不是另一个。

var model = {
    crags: [{
        name: "Stanage",
        cragColor: "'#FF0000'",
        coords: [new google.maps.LatLng(53.360470, -1.646050),
        new google.maps.LatLng(53.359523, -1.647895),
        new google.maps.LatLng(53.351006, -1.637123),
        new google.maps.LatLng(53.351364, -1.627167)]
    }, {
        name: "Burbage",
        cragColor: "'#00AA00'",
        coords: [new google.maps.LatLng(53.341489, -1.606224),
        new google.maps.LatLng(53.338148, -1.605190),
        new google.maps.LatLng(53.338145, -1.600849),
        new google.maps.LatLng(53.341501, -1.604020)]
    }, {
        name: "Higgar",
        cragColor: "'#0000BB'",
        coords: [new google.maps.LatLng(53.340912, -1.611288),
        new google.maps.LatLng(53.338048, -1.612833),
        new google.maps.LatLng(53.339762, -1.608670)]
    }]
}

getCragName: function (index) {
    return model.crags[index].name;
}

$.each(controller.getCrags(), function (index, value) {
    var polygon = new google.maps.Polygon({
        paths: value.coords,
        strokeColor: value.cragColor,
        strokeOpacity: 0.8,
        strokeWeight: 3,
        fillColor: value.cragColor,
        fillOpacity: 0.35
    });
    polygons.push(polygon);
    polygon.setMap(map);
});

完整的代码可以在这个jsfiddle中找到 http://jsfiddle.net/erskmcha/

2 个答案:

答案 0 :(得分:2)

问题不在于作用域或闭包,而是因为你在color属性中“双重包裹”了字符串:

cragColor: "'#FF0000'",

应该是:

cragColor: "#FF0000",

Updated fiddle

答案 1 :(得分:1)

真的很容易解决。你有额外的'这会造成伤害。

变化:

    cragColor: "'#0000BB'",

要:

    cragColor: "#0000BB",

你已经完成了

相关问题