<span> 标签的 jQuery 增量值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7698729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 00:10:55  来源:igfitidea点击:

jQuery increment value of <span> tag

jquery

提问by user978905

I have a number in a span tag. I need to get the value of the number in the span and then increment it inside jQuery. I know how to do this for a text input - can this be done to a span tag?

我在 span 标签中有一个数字。我需要获取跨度中数字的值,然后在 jQuery 中增加它。我知道如何为文本输入执行此操作 - 可以对 span 标签执行此操作吗?

SPAN tag

SPAN 标签

<span class="changeNumber"> 33 </span>

jQuery span selector

jQuery 跨度选择器

var commentNumAppend = $(this).closest(".songContainer").find(".changeNumber");

回答by Jayendra

Example -

例子 -

<span class="changeNumber">33</span>

$('.changeNumber').html(parseInt($('.changeNumber').html(), 10)+1)

回答by Only Bolivian Here

You can do something like:

您可以执行以下操作:

var value = parseInt($(".changeNumber").text(), 10) + 1;
$(".changeNumber").text(value);

JsFiddle Example:

JsFiddle 示例:

http://jsfiddle.net/stapiagutierrez/WXAvS/1/

http://jsfiddle.net/stapiagutierrez/WXAvS/1/

References:

参考:

  1. parseInt()
  2. text()
  1. parseInt()
  2. text()

回答by Jess

This is the most complete answer.

这是最完整的答案。

  1. This solution avoids selector repetition
  2. Handles the increment gracefully if the span does not have a value yet.
  1. 此解决方案避免了选择器重复
  2. 如果跨度还没有值,则优雅地处理增量。
<span class="changeNumber"></span>
var $number = $('.changeNumber');
$number.html((parseInt($number.html(),10) || 0) + 1);

回答by Matt Ball

Something like this:

像这样的东西:

var $span = $('#mySpanId');
$span.text(Number($span.text()) + 1);

http://jsfiddle.net/mattball/Cf834/

http://jsfiddle.net/mattball/Cf834/

回答by Rafay

var spanVal=$("span").html();
if(!isNaN(spanVal)){

alert("value incremented"+ (++spanVal));
}

http://jsfiddle.net/c84F4/

http://jsfiddle.net/c84F4/

回答by Dipendra Kumar Mishra

$(".changeNumber").html(parseInt($(".changeNumber").html())+1)

回答by Sparky

I assume you mean something like this?

我猜你的意思是这样的?

<span id="Nbr">123</span>

If so, the InnerHTML property will give you the content of the span

如果是这样,InnerHTML 属性将为您提供跨度的内容