【问题标题】:Get value of span with jquery使用 jquery 获取 span 的值
【发布时间】:2019-01-01 01:21:57
【问题描述】:

好的,所以我正在使用 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 获取 true 案例中的跨度值:

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

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

谢谢!

【问题讨论】:

  • span 元素没有值。您可以使用text() 获取他们的内部文本,或者使用html() 获取他们的内部html
  • 我不知道,谢谢!
  • 这里是您要求的链接。 stackoverflow.com/questions/1921342/…

标签: jquery html spring-boot thymeleaf


【解决方案1】:

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

<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);
    });});

【讨论】:

  • 谢谢,工作几乎完美,只需修改&lt;span class="glyphicon glyphicon-remove" aria-hidden="true" th:attr="data-value=${cost.cost_id}" &gt; 只是添加数据值不起作用
  • 是的。这是因为您正在使用模板.. :)
猜你喜欢
  • 2010-12-27
  • 2013-12-21
  • 2013-09-01
  • 1970-01-01
  • 2015-04-05
  • 2017-06-29
  • 2014-11-18
  • 2012-11-03
  • 2011-10-18
相关资源
最近更新 更多