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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 05:48:15  来源:igfitidea点击:

How to get number inside a div with jquery

javascriptjqueryhtml

提问by Chipe

How do I get a number inside a divand use it as a numberin JavaScript/jQuery? Here is what I have:

如何在 a 中获取一个数字div并将其用作numberJavaScript/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 divs. You can use .text()to get the text content of the divelement.

.val()对于获取表单元素的值inputselect等等。你不能用它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));