Обработка события щелчка мыши на строке таблицы
Здравствуйте!
Подскажите пожалуйста как мне обработать событие щелчок мыши на строке таблицы, если у мне заранее не известно сколько строк в данной таблице будет? У меня есть JSP-файл, в котором в <table> подтягиваются данные из базы данных, количество записей заранее не известно. Нужно чтобы при щелчке мыши на строку бралось значение ячейки (geographkoords) из этой ячейки и передавалось в функцию (UpdateGoogleMap).
<html>
<head>
<title>Главная страница</title>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 50%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
}
</style>
<script>
var map, marker;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(51.754207,55.106578),
zoom: 8
});
}
function UpdateGoogleMap(latitude, longitude) {
latitude = (latitude && +latitude)||51.754207;
longitude = (longitude && +longitude)||55.106578;
map.setCenter({
lat: latitude,
lng: longitude
});
marker && marker.setMap(null);
marker=new google.maps.marker({
position: {
lat: latitude,
lng: longitude
},
map: map,
title: 'Это здесь'
});
};
</script>
<!-- -->
<script src="https://maps.googleapis.com/maps/api/js?key=ххх&callback=initMap"
async defer></script>
</head>
<body>
<div>
<table>
<thead>
<tr>
<th>idPost</th>
<th>namePost</th>
<th>distanceBeetwenSensors</th>
<th>geographkoords</th>
</tr>
</thead>
<tbody>
<c:forEach items="${listPosts}" var="post">
<tr>
<td>${post.idPost}</td>
<td>${post.namePost}</td>
<td>${post.distanceBeetwenSensors}</td>
<td>${post.geographkoords}</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
<div id="map"></div>
</body>
</html>
|
addEventListener("click", ({target}) => {
var tr = target.closest("tbody > tr");
if(!tr) return;
var position = tr.querySelector("td:last-child").textContent;
alert(position)
});
|
рони,
Спасибо! А куда этот слушатель нужно вешать? |
Цитата:
|
Цитата:
|
Цитата:
Цитата:
|
Цитата:
|
Цитата:
Там мы должны вызвать функцию UpdateGoogleMap и передать в неё данные из ячейки? |
Цитата:
|
Цитата:
|
Цитата:
Формат данных такой как указал здесь в примере:
<html>
<head>
<title>Главная страница</title>
<style>
#map {
height: 50%;
}
html, body {
height: 100%;
}
</style>
<script>
var map, marker;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(51.754207,55.106578),
zoom: 8
});
}
function UpdateGoogleMap(latitude, longitude) {
latitude = (latitude && +latitude)||51.754207;
longitude = (longitude && +longitude)||55.106578;
map.setCenter({
lat: latitude,
lng: longitude
});
marker && marker.setMap(null);
marker=new google.maps.marker({
position: {
lat: latitude,
lng: longitude
},
map: map,
title: 'Это здесь'
});
};
</script>
<!-- -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCWH__g2XMzhes7PIk-8v2MbBSZTgMnBSg&callback=initMap"
async defer></script>
</head>
<body>
<div>
<table>
<thead>
<tr>
<th>idPost</th>
<th>namePost</th>
<th>distanceBeetwenSensors</th>
<th>geographkoords</th>
</tr>
</thead>
<tbody>
<c:forEach items="${listPosts}" var="post">
<tr>
<td>1</td>
<td>г.Самара</td>
<td>2</td>
<td>55.09 52.07</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
<div id="map"></div>
</body>
</html>
|
Vladiiimir,
ждите... |
Vladiiimir,
проверьте
<script>
var map, marker;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(51.754207,55.106578),
zoom: 8
});
}
function UpdateGoogleMap(latitude, longitude) {
latitude = (latitude && +latitude)||51.754207;
longitude = (longitude && +longitude)||55.106578;
map.setCenter({
lat: latitude,
lng: longitude
});
marker && marker.setMap(null);
marker=new google.maps.Marker({
position: {
lat: latitude,
lng: longitude
},
map: map,
title: 'Это здесь'
});
};
addEventListener("click", ({target}) => {
var tr = target.closest("tbody > tr");
if(!tr) return;
var position = tr.querySelector("td:last-child").textContent;
position = position.split(/\s+/).map(Number);
UpdateGoogleMap(...position)
});
</script>
|
Цитата:
|
Цитата:
Можете прокомментировать, что значит переменная target? Что мы делаем в строках:
var position = tr.querySelector("td:last-child").textContent;
position = position.split(/\s+/).map(Number);
|
Vladiiimir,
вы поменяли расположение ячейки с данными!!! сделайте ячейке класс например <td class="geo">55.09 52.07</td> и тогда
var position = tr.querySelector("td.geo").textContent;
|
Vladiiimir,
или так
var position = tr.querySelector("td:nth-child(4)").textContent;
|
Цитата:
А можно вот как мы сделали привязку к ячейке <td class="geo">55.09 52.07</td>, аналогично сделать привязку слушателя к таблице? |
Цитата:
|
Цитата:
|
Vladiiimir,
document.querySelector('table.класс_нужной_таблицы').
addEventListener("click", ({target})
|
Цитата:
Странная политика на сайте - нельзя поставить 2-ой "+" человеку пока не поставишь кому-нибудь другому ) |
| Часовой пояс GMT +3, время: 19:51. |