怎样才能使用jquery从文本中获取数字 [英] how can get only numbers from the text using jquery

查看:89
本文介绍了怎样才能使用jquery从文本中获取数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想只得到数字(123)而不是文本(确认),这是我的代码

I want to get only the numbers(123) not the text(confirm), here is my code

<p>123confirm</p>

<script type="text/javascript">
$(document).ready(function(){  
  $('p').click(function(){  
    var sd=$(this).text();  
    alert(sd);
  });
});  
</script>


推荐答案

您可以使用 parseInt 为此,它将解析一个字符串并删除其中的任何垃圾并返回一个整数。

You can use parseInt for this, it will parse a string and remove any "junk" in it and return an integer.

正如James Allardice所注意到的,这个数字必须在字符串之前。因此,如果它是文本中的第一件事,它将起作用,否则它不会。

As James Allardice noticed, the number must be before the string. So if it's the first thing in the text, it will work, else it won't.

- 编辑 - 与你的例子一起使用:

-- EDIT -- Use with your example:

<p>123confirm</p>

<script type="text/javascript">
$(document).ready(function(){  
  $('p').click(function(){  
    var sd=$(this).text();  
    sd=parseInt(sd);
    alert(sd);
  });
});  
</script>

这篇关于怎样才能使用jquery从文本中获取数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆