使用jQuery,我想从中提取一个数字<span>并使用它来计算新值。
<div class="post-100" data-postid="100">
<span class="score">3</span>
</div>
Run Code Online (Sandbox Code Playgroud)
我已经有了基本的想法,但是我不知道如何引用现有的span值:
if (response.newvoteid == null)
{
$(".post-" + $(this).data("postid") + " .score").text(
parseInt( **EXISTING VALUE + 1 OR -1**));
}
Run Code Online (Sandbox Code Playgroud)
更新:我现在正在使用以下无法计算新值的方法,只是在文本中添加了一个数字。例如,<span class="score">3</span>变为<span class="score">31</span>
var number = $(".post-" + $(this).data("postId") + " .score").text();
$(".post-" + $(this).data("postId") + " .score").text(number + 1);
Run Code Online (Sandbox Code Playgroud)
parseInt()是一个辅助方法,它要求将字符串作为这样的参数进行解析:
parseInt($(".score").text())
Run Code Online (Sandbox Code Playgroud)
要进行计算,您现在可以将您的数字添加到parseInt()的结果中:
var newVal = parseInt($(".score").text()) + 1
Run Code Online (Sandbox Code Playgroud)
我不清楚,您想如何选择跨度。你能解释清楚一点吗?
上面的代码例如通过其类选择跨度的内容。
只需传递一个函数即可.text()返回递增(或递减)的旧值:
$(".post-" + $(this).data("postid") + " .score").text( function( i, txt ) {
return ( parseInt( txt, 10 ) + 1 ); // Returns the old value,
}); // plus (or minus) 1.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9510 次 |
| 最近记录: |