首页 > 解决方案 > 使用 jquery 获取 span 的值

问题描述

好的,所以我正在使用 Spring boot 开发一个 Web 项目,并使用 Thymeleaf 作为模板引擎,在一页中我有以下内容:

[...]<span   th:switch="${cost.achitat}" class="pull-right">                                    
  <span th:case='true'  class="btn btn-xs btn-default" >
    <span class="glyphicon glyphicon-remove" aria-hidden="true" th:value="${cost.cost_id}"></span>
  </span> 
  <span th:case='false' class="btn btn-xs btn-default">
    <span class="glyphicon glyphicon-ok" aria-hidden="true"></span>
  </span> 
</span>[...]

(对象的“achitat”参数是布尔值,我在更高的 div 中有一个 th:each,如果我使用 th:text 设置文本,它会在我的页面上正确显示,因此正在传输该值)

我正在尝试使用 jquery在真实案例中获取跨度的值:

$(document).ready(function(){
$('.glyphicon.glyphicon-remove').click(function(){
    var t = $(this).val();
    alert(t);
});});

但是警报总是空的。我知道以前曾以某种形式提出过这个问题,但我找不到解决方案,也不知道我做错了什么。

谢谢!

标签: jqueryhtmlspring-bootthymeleaf

解决方案


请注意,只有输入才有值。其他你必须使用数据属性。

<span class="glyphicon glyphicon-remove" aria-hidden="true" th:attr="data-value=${cost.cost_id}"></span>

    $(document).ready(function(){
    $('.glyphicon.glyphicon-remove').click(function(){
        var t = $(this).data('value'); // if int the use parseInt() function;
        var t = paerseInt($(this).data('value'));
        alert(t);
    });});

推荐阅读