简体   繁体   中英

How to access a particular element from JSTL ForEach tag using javaScript?

I'm trying to make a booking website. On my jsp page, I have a jstl forEach that loops through multiple pictures from my database of various events. These images act as links, every image has a different link attached.

I also want to send location coordinates along with image to sort through database based on region, hence I am using Javascript.

How can I access an individual image in my javascript, to redirect to corresponding page?

I have tried using 'alt' of image, but that returns same value (alt of first image in loop) on every image in javaScript. However if I use href in anchor tags, the correct value is returned for every link. Is there a solution where I can use 'alt' in javaScript.

jsp:

<core:forEach items="${requestScope.Events}" var="Events">
 <div>
  <a onClick="getLocation()">
   <img alt="${Events.name}" src="/images/${Events.name).jpg">
  </a>
 </div>
</core:forEach>

Expected result is to get javascript:getLocation() have details of selected image so that it can be forwarded along with location coordinates to display nearby events according to user's location.

You can pass the name in the call to the event handler:

<core:forEach items="${requestScope.Events}" var="Events">
 <div>
  <a onClick="getLocation('${Events.name}')">
   <img alt="${Events.name}" src="/images/${Events.name).jpg">
  </a>
 </div>
</core:forEach>

Your handler function would then be modified to accept the event name as a parameter.

FWIW I'd use a <button> instead of <a> here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM