jQuery:如何获取跨度的内容,减去 1,然后用新数字替换跨度的内容?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1180442/
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
jQuery: How do I get the contents of a span, subtract by 1, and replace contents of span with new number?
提问by dallen
Let's say I have a PHP loop that displays data that you can delete. I'm using AJAX, so when you delete a row, it processes a PHP script and the row disappears from the page.
假设我有一个 PHP 循环,它显示您可以删除的数据。我正在使用 AJAX,因此当您删除一行时,它会处理一个 PHP 脚本,并且该行会从页面中消失。
However, I have something that says "There are 5 items". I'd like that "5" to change when an item is deleted. I figured the easiest way would be to subtract by one in Javascript.
但是,我有一些东西说“有 5 个项目”。我希望在删除项目时更改“5”。我认为最简单的方法是在 Javascript 中减一。
Problem is, I really don't know how. If someone could point me in the right direction, that would be great.
问题是,我真的不知道怎么办。如果有人能指出我正确的方向,那就太好了。
回答by drs9222
Assuming the count is in a span with id 'cnt':
假设计数在 id 为“cnt”的范围内:
$("#cnt").text($("#cnt").text()-1)
Edit:
Safer Version:
编辑:
更安全的版本:
var cntTag = $("#cnt:first");
if (cntTag.Length == 1)
{
var cnt = parseInt(cntTag.text());
if (!isNaN(cnt))
{
cnt--;
cntTag.text(String(cnt));
}
}
回答by edsoverflow
HTML:
HTML:
There are <span class="numitems">5</span> items.
JS:
JS:
var span = $("span.numitems");
span.html(parseInt(span.html()) - 1);
回答by Scott Baker
Let's say we start with three:
假设我们从三个开始:
<p>There are <span id='number'>3</span> items.</p>
<ol id ='thelist'>
<li> one
<li> two
<li> three
</ol>
Now we need some jQuery to handle the change event on the list
现在我们需要一些 jQuery 来处理列表上的更改事件
$(function(){
$('#thelist').bind('change', function(){
$('#number').html($('#thelist li').length)
}
}
every time #thelist changes, it will update the length in #number. One advantage to this approach is that by binding the change event, you don't need to setInterval on a timer or anything like that. Everything just does what its supposed to.
每次#thelist 更改时,它都会更新#number 中的长度。这种方法的一个优点是通过绑定更改事件,您不需要在计时器或类似的东西上设置间隔。一切都只是做它应该做的。
回答by Scott Baker
Update the complete list if there has something changed. Check it using AJAX about every 5 seconds.
如果有任何变化,请更新完整列表。大约每 5 秒使用 AJAX 检查一次。
Or
或者
There are <span id="number">5</span> items.
and then change the value of span with id 'number' with the current number of rows after deletion. Stack Overflow uses this method when a new answer is posted when you are adding a new one.
然后将 id 为 'number' 的 span 值更改为删除后的当前行数。当您添加新答案时发布新答案时,Stack Overflow 会使用此方法。
You can substract using
您可以减去使用
parseInt($("span").html());