javascript 如何使用jquery获取div内的数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26319183/
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
How to get number inside a div with jquery
提问by Chipe
How do I get a number inside a div
and use it as a number
in JavaScript/jQuery? Here is what I have:
如何在 a 中获取一个数字div
并将其用作number
JavaScript/jQuery 中的 a?这是我所拥有的:
HTML:
HTML:
<div class="number">25</div>
jQuery:
jQuery:
var numb = $('.number').val();
console.log(numb);
jsfiddle: http://jsfiddle.net/nw9rLfba/
jsfiddle:http: //jsfiddle.net/nw9rLfba/
回答by Arnelle Balane
.val()
is for getting the value of form elements like input
, select
, etc. You can't use it on div
s. You can use .text()
to get the text content of the div
element.
.val()
对于获取表单元素的值input
,select
等等。你不能用它div
秒。您可以使用.text()
来获取div
元素的文本内容。
var number = $('.number').text();
But it will return the content as a string. To convert it to a Javascript number, you have to use parseInt()
:
但它会将内容作为字符串返回。要将其转换为 Javascript 数字,您必须使用parseInt()
:
var number = parseInt($('.number').text());
回答by Wojciech Mleczek
var numb = $('.number').text();
console.log(parseInt(numb));