如何使用多个数组元素'用于'在JQuery中

时间:2014-03-20 19:19:00

标签: javascript jquery html json leaflet

我正在尝试将数组中的多个值传递给for语句,它目前只处理最后一个值。结果是,它为巴西国家而不是巴西美国提供了色彩。如何在不多次运行的情况下将多个值传递给函数? 这是一个小提琴:http://jsfiddle.net/J4643/

这是JS:

var colourCountries = ["United States of America","Brazil"];
var mapboxTiles = L.tileLayer('https://{s}.tiles.mapbox.com/v3/alexplummer.him2149i/{z}/{x}/{y}.png');
var map = L.map('map')
.addLayer(mapboxTiles)
.setView([30, 0], 3);
function style(feature) {
for (var i=1; i<= colourCountries.length; i++) {
 if (colourCountries[i] == feature.properties.name) {
   return {
   weight: 2,
   opacity: 1,
   color: 'white',
   dashArray: '3',
   fillOpacity: 0.3,
   fillColor: '#ff0000'
 };
 } 
     else {
   return {
   weight: 1,
   opacity: 1,
   color: '#32B3EF',
   fillOpacity: 1,
   fillColor: '#F3F4E8'
 };
 }
}
}       
var geojson, thisCountry;
function onEachFeature(feature, layer) {}
geojson = L.geoJson(countryData, {
    onEachFeature: onEachFeature,
    style: style
}).addTo(map);

1 个答案:

答案 0 :(得分:1)

有2个错误。数组索引从0开始而不是1.也就是它的编写方式,循环总是在第一圈返回。这有效:

function style(feature) {
  for (var i=0; i < colourCountries.length; i++) {
    if (colourCountries[i] == feature.properties.name) {
      return {
        weight: 2,
        opacity: 1,
        color: 'white',
        dashArray: '3',
        fillOpacity: 0.3,
        fillColor: '#ff0000'
      };
    }
  }

  return {
    weight: 1,
    opacity: 1,
    color: '#32B3EF',
    fillOpacity: 1,
    fillColor: '#F3F4E8'
  };
}       

<强> Live Demo

可替换地:

function style(feature) {
  var style1 = {
    weight: 2,
    opacity: 1,
    color: 'white',
    dashArray: '3',
    fillOpacity: 0.3,
    fillColor: '#ff0000'
  };
  var style2 = {
    weight: 1,
    opacity: 1,
    color: '#32B3EF',
    fillOpacity: 1,
    fillColor: '#F3F4E8'
  };

  if ( colourCountries.indexOf(feature.properties.name) !== -1) {
    return style1;
  } 
  return style2;
}