我正在春季编写程序,其中一个方面是犯罪评级功能。根据用户输入,API查询和一些计算,我得出的评分为10。就像这样(加尔达警察局是爱尔兰的警察局)
我认为如果数字的颜色发生变化(例如,低分变为绿色,高分变为红色等)会很酷。我正在Spring应用程序中从Controller类打印此信息。我尝试了以下方法:
我向<b>
标签添加了ID,以将值传递到javascript变量中,如下所示:
<c:forEach var="o" items="${gardaStationList}">
<tr>
<td width="10%" height="50"><h2>Based on <b><c:out value="${o.gardaStation_name}" /></b> and their statistics
the rating for this area is: <b id = "rating"><c:out value="${o.crime_rating}" /></b></h2></td>
</tr>
</c:forEach>
当页面加载时,我让它运行以下javascript函数,但是我感觉它是在评级加载之前执行此操作的,所以它不起作用?
window.onload = function() {
var rating = document.getElementById('rating').value;
if (rating < 4) {
document.getElementById("rating").style.color = "#45FD00";
} else if (rating > 4 && rating < 6) {
document.getElementById("rating").style.color = "#E6E6E6";
} else if (rating > 6) {
document.getElementById("rating").style.color = "#ff0000";
}
}
有没有办法可以在文本加载后运行该函数,或者我做错了吗?
您走在正确的道路上,但只有表单字段元素具有.value
属性。常规元素具有.textContent
属性。
而不是b
使用span
,它更适合于包含一些内联内容。要使样式变粗体,请使用CSS。
接下来,为每个将包含数据的元素提供所需的通用CSS类名称,以将它们分组在一起,而不是id
在各个元素上使用unique 。这样就很容易将它们全部收集起来,或者以后再添加,而无需更改JavaScript。
另外,使用CSS类而不是创建动态的内联样式,因为类更加灵活并且允许您使用element.classList
对象,这使得添加,删除和切换类变得容易。
// When all the HTML has been parsed and is available...
window.addEventListener("DOMContentLoaded", function() {
// Get all the ratings into an array
var ratings = Array.prototype.slice.call(document.querySelectorAll('.rating'));
// Loop over the array
ratings.forEach(function(r){
// Get the text that is inside the element
var val = +r.textContent; // The prepended + converts the text to a number
// Just add the appropriate pre-made CSS class to the element
// depending on its text content.
if(val < 4 ){
r.classList.add("low");
} else if(val >= 4 && val <= 6){
r.classList.add("medium");
} else if(val > 6){
r.classList.add("high");
}
});
});
.rating { font-weight:bold; }
.low { color:#45FD00; }
.medium { color:#880; }
.high { color:#ff0000; }
td { width:10%; height:50px; }
<table>
<tr>
<td><h2>Based on statistics the rating for this area is: <span class="rating">10.04</span></h2></td>
</tr>
<tr>
<td><h2>Based on statistics the rating for this area is: <span class="rating">5.4</span></h2></td>
</tr>
<tr>
<td><h2>Based on statistics the rating for this area is: <span class="rating">0.4</span></h2></td>
</tr>
</table>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句