开发者

Get element value and then subtract by 1?

开发者 https://www.devze.com 2023-04-11 03:00 出处:网络
<span id=\"tcount-1\">100</span> <span id=\"tcount-2\">100</span> <span id=\"tcount-3\">100</span>
<span id="tcount-1">100</span>  
<span id="tcount-2">100</span>
<span id="tcount-3">100</span>

What I am trying to do is grab the value within span id=tcount-X (where X can be any ID value) and then subtract 1 from it.

So I know I can easily hide the value by doing...

$('span#tcount-' + com_id).hide();

but as soon as I do something like...

var countit = $('sp开发者_JAVA百科an#tcount-' + com_id).val();

... it breaks. Any ideas what I'm doing wrong?


var s = $('span#tcount-' + com_id);
s.html(s.text()*1 - 1);

Regarding using *1 instead of parseInt see the problems with this:

Get element value and then subtract by 1?


(source: phrogz.net)

and the performance impacts here:
http://jsperf.com/convert-string-to-number-techniques

(You don't actually need the *1 since you're subtracting, but I've included it on the assumption that at some point you might want to add 1, at which point you'll run into string concatenation issues unless you convert the string to a number first.)


.val() for setting form fields. What you want is .text(), which will retrieve the CONTENTS of the span, not its "value" (spans can't have values, in any case). Note that this will retrieve the contents as a string, so you will need to parseInt() and whatnot to do your math.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号