【问题标题】:OnClick event for button only works on first row of table按钮的 OnClick 事件仅适用于表格的第一行
【发布时间】:2018-06-26 14:52:02
【问题描述】:

我正在使用 Google 地图地理编码从我的 JSP 页面上的表格行中搜索和显示地址。该地址是从会话密钥中检索的。每行都有一个地址和一个按钮,但目前该按钮仅适用于第一行中的地址。我是新手,如果术语不正确,请致歉。

会话密钥代码:

<tbody>
<c:forEach items="${SKALLUSERS}" var="tempuser">    
    <tr>
        <td scope="row"><c:out value="${tempuser.getId()}"/></td>
            <td>${tempuser.id}</td>
            <td>${tempuser.email}</td>
            <td>${tempuser.password}</td>
            <td>${tempuser.firstName}</td>
            <td>${tempuser.lastName}</td>
            <td>${tempuser.userType}</td>
            <td><input id="address" type="textbox" 
            value="${tempuser.address}"></td>
            <td><a href="updateUser.jsp">Update</a></td>
            <td><input id="submit" type="button" value="Geocode"></td>
    </tr>
</c:forEach>
</tbody>

谷歌地图地理编码

<div id="floating-panel"></div>
<div id="map"></div>

<script>
    function initMap() {
    var map = new google.maps.Map
    (
        document.getElementById('map'), 
        {
            zoom: 8,
            center: {lat: -34.397, lng: 150.644}
        }
   );
   var geocoder = new google.maps.Geocoder();

   document.getElementById('submit').addEventListener
   (
       'click', function() 
       {
          geocodeAddress(geocoder, map);
       }
   );
  }

  function geocodeAddress(geocoder, resultsMap) 
  {
      var address = document.getElementById('address').value;
      geocoder.geocode({'address': address}, function(results, status) 
      {
      if (status === 'OK') 
      {
          resultsMap.setCenter(results[0].geometry.location);
          var marker = new google.maps.Marker
          ({
              map: resultsMap,
              position: results[0].geometry.location
          });
      }
      else 
      {
          alert('Geocode was not successful for the following reason: + status);
      }
    });
  }
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCH2nCSs1XR37Q6HdyUpZZfgP5_uMsi-vA&callback=initMap">
</script>

【问题讨论】:

  • 这两种方法都不起作用,因为您选择了找到的第一个元素。如果您可以从元素集合映射以将会话密钥返回给函数,那么您可以在结果映射中使用 asiync 不同的地理编码。

标签: html jsp google-geocoding-api session-keys


【解决方案1】:

绝不是专家,我可能错了,但据我所知,id 应该是唯一的。

尝试为您的提交按钮添加一个类或为 id 添加一个索引,例如“submit1”、“submit2”,然后使用:您拥有的 addEventListener

document.getElementById('submit').addEventListener

但是使用另一个其他选择器,例如 getElementsByClassName 或使用当前选择器,如果您添加索引但获取所有 id 以“提交”开头的元素。

【讨论】:

    【解决方案2】:

    绝不是专家,我也可能错了。

    但是如果只有 forEach 循环中表格第一行中的按钮按您所说的那样工作,那么其余的也应该工作。

    除了您循环的数据(即items="${SKALLUSERS}")可能不正确,例如导致表格第一行的第一项是唯一具有预期值的项,而其余的不是.

    【讨论】:

      猜你喜欢
      • 2016-11-05
      • 1970-01-01
      • 1970-01-01
      • 2019-01-12
      • 1970-01-01
      • 2021-03-25
      • 2018-05-19
      • 2012-09-10
      • 1970-01-01
      相关资源
      最近更新 更多