Таблица из массива, скрыть пустые строки - PullRequest
0 голосов
/ 11 апреля 2020

Для карты Google Maps я попытался заполнить информационное окно массивом. Если значение отсутствует в массиве, полная строка отображаться не должна.

Например: если в массиве нет электронного письма, строка «Email:» вообще не должна отображаться. Я попытался решить эту проблему с помощью следующего кода:

Тем не менее, я полный новичок в Javascript и, к сожалению, он не работает.

var locations = [
  ['Bondi Beach', -33.890542, 151.274856, 'City' , 'Country', '+39 0584 430461', 'info@centronauticocom.com', 'www.centronauticocom.com'],
  ['Coogee Beach', -33.923036, 151.259052],
];

  google.maps.event.addListener(marker, 'click', (function(marker, i) {
    return function() {
      infowindow.setContent
				
				('<div class="inside">' + '<span>' + locations[i][0] +'</span>' + locations[i][3] + ' • ' + locations[i][4] + '<table><tbody>' + 
 if (locations[i][5] !== null) { '<tr><td width="60">Tel.:</td><td><a href="tel:' + locations[i][5] + '">' + locations[i][5] + '</a></td></tr>'} + 
 if (locations[i][6] !== null) { '<tr><td width="60">Email:</td><td><a href="mailto:' + locations[i][6] + '">' + locations[i][6] + '</a></td></tr>' } + 
  if (locations[i][7] !== null) { '<tr><td width="60">Web:</td><td><a href="http://' + locations[i][7] + '" target="_blank">' + locations[i][7] + '</a></td></tr>' } + '</tbody></table>' + '</div>'	 
														 
														 );
      infowindow.open(map, marker);
    }
  })(marker, i));
}

1 Ответ

1 голос
/ 11 апреля 2020

Вы можете использовать троичный оператор , но в этом случае я считаю, что лучше разделять операторы if. Я также использую шаблонные литералы , чтобы сделать код более понятным.

var locations = [
  ['Bondi Beach', -33.890542, 151.274856, 'City', 'Country', '+39 0584 430461', 'info@centronauticocom.com', 'www.centronauticocom.com'],
  ['Coogee Beach', -33.923036, 151.259052]
];

function getDescription(i) {
  var result = `<div class="inside">
    <span>${locations[i][0]}</span>
    ${locations[i][1]} • ${locations[i][2]}<table><tbody>`;
  if (locations[i][5]) result += `<tr><td width="60">Tel.:</td>
    <td><a href="tel:${locations[i][5]}">${locations[i][5]}</a></td></tr>`;
  if (locations[i][6]) result += `<tr><td width="60">Email:</td>
    <td><a href="mailto:${locations[i][6]}">${locations[i][6]}</a></td></tr>`;
  if (locations[i][7]) result += `<tr><td width="60">Web:</td>
    <td><a href="http://${locations[i][7]}" target="_blank">
    ${locations[i][7]}</a></td></tr>`
  result += `</tbody></table></div>`;
  return result;
}

console.log(getDescription(0));
console.log(getDescription(1));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...