【发布时间】:2018-02-15 11:33:01
【问题描述】:
我在按钮点击的卡片上显示每个城市的天气数据
JSP 页面
<c:forEach var="list" items="${listHist}">
<div class="w3-container">
<ul class="w3-ul w3-card-4">
<li class="w3-bar">
<span onclick="this.parentElement.style.display='none'" class="w3-bar-item w3-button w3-white w3-xlarge w3-right">×</span>
<img src="resources/assets/images/a1.png" class="w3-bar-item w3-circle w3-hide-small" style="width:85px">
<div class="w3-bar-item">
<span><font size="6">Name : ${list.name}</font></span><br>
<span>
<ul><li class="card-text">Ticket Number : ${list.ticketNo}
<li class="card-text">From : ${list.fromCity}
<li class="card-text">To : ${list.toCity}
<li class="card-text">Date : ${list.travelDate}
<li class="card-text">Travel Class : ${list.travelClass}
<li class="card-text">Gender : ${list.gender}
<li class="card-text">Passenger type : ${list.ptype}
<li class="card-text">Price : ${list.price}
<p id="weatherdata"></p>
</li>
</ul>
</span>
<font color="white"><button type="button" class="btn btn-danger" onclick="currWeather("${list.toCity}");myFunction();" style="margin-left: 0px ">Weather</button></font>
</div>
</div>
</c:forEach>
我的脚本: 我使用了 jquery 天气脚本,其中使用了 yahoo api 来获取该城市的天气数据
function currWeather(city){
var city =city;
$(document).ready(function() {
$.simpleWeather({
location: city+', IN',
woeid: '',
unit: 'c',
success: function(weather) {
$("p").slideToggle();
/* $("div") */
document.getElementById("weatherdata").innerHTML=weather.code+" "+weather.temp+ " "+weather.units.temp+" "+weather.currently;
},
error: function(error) {
document.getElementById("weatherdata").innerHTML=error;
}
});
});
}
问题: 函数中的数据总是显示在第一张卡片上,即使按下其他卡片上的按钮也是如此。点击按钮后,我想在每张卡片上单独显示天气数据。
【问题讨论】:
-
您需要为“weatherdata”设置一个唯一 ID,以便仅使用该 ID 附加数据。当使用 getElementById 时,具有相同 id 的重复控件将始终只返回第一个控件。
-
是的,但问题是我们从 spring mvc 控制器获取列表值,我们无法为项目列表中的每个项目提供 id 请检查我的 for:each 循环
-
你试过
<p id="weatherdata_#{loop.count}"></p>甚至<p id="weatherdata_${list.name}"></p> -
@Yasir 有些人喜欢真是天才 OMG!请发布一个答案我会验证你的答案,因为它完全适合我
标签: javascript jquery spring-mvc jstl