开发者

Can I get value as number?

开发者 https://www.devze.com 2023-02-27 01:11 出处:网络
I have a few elements with numeric IDs. Each ID is in a separate span. Can I get that value as a number in order to increment? I tries as text but it does not seem to work...

I have a few elements with numeric IDs. Each ID is in a separate span. Can I get that value as a number in order to increment? I tries as text but it does not seem to work...

var lastVal = $(".myID:last").text(开发者_如何学编程); 
var newVal  = lastVal++;

Value <span class="myID">5</span>


Convert a string to a number in js like so:

var num = parseInt(lastVal, 10);


When you get the .text() of an element, jQuery returns a string. You can't increment a string, so you'll have to make it an integer using the parseInt() function:

var lastVal = parseInt($(".myID:last").text(), 10);

Now lastVal contains an integer.


To convert a string to a number, you can use the parseInt function. But to actually change it (if I understand your intent correctly), you want to do:

var elem = $('.myID');
var num = parseInt(elem.text());
elem.text(num+1)

// <span class="myID">5</span>


Use the parseInt function to convert it from a string to a number:

var newVal  = parseInt(lastVal, 10);
newVal++;

The second parameter to parseInt, radix, is optional and is used specify the base of your input string. Failure to supply this parameter causes the base to be determined automatically according to the following rules:

  • If the string begins with "0x", the base is assumed to be 16.
  • If the string begins with "0", the base is assumed to be 8.
  • If the string begins with anything else, the base is assumed to be 10.


Couple things here:

$('#btn').click(function(){
   var lastVal = parseInt($("#txt").val(), 10); 
   var newVal  = ++lastVal;
})
  1. You can use parseInt to get the numeric value from the text
  2. Try pre-incrementing opposed to post here. Using post increment, you're assigning the value of lastVal to newVal and then incrementing (which doesn't get added). Using pre increment, you modify the value of lastVal before assignment (which is what you're looking to do).

Sample here

0

精彩评论

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

关注公众号