jQuery / 从字符串中获取数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9282935/
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
jQuery / Get numbers from a string
提问by TheCarver
I have a button on my page with a class of comment_like
and an ID like comment_like_123456
but the numbers at the end are variable; could be 1 to 1000000.
我的页面上有一个按钮,类comment_like
和 ID 类似,comment_like_123456
但最后的数字是可变的;可以是 1 到 1000000。
When this button is clicked, I need to grab the end number so I can run tasks on other elements with the same suffix.
单击此按钮时,我需要获取结束编号,以便我可以在具有相同后缀的其他元素上运行任务。
Is there an easy way of grabbing this number in jQuery?
有没有一种简单的方法可以在 jQuery 中获取这个数字?
$('.comment_like').click(function() {
var element_id = $(this).attr('id');
// grab number from element ID
// do stuff with that number
});
回答by Sarfraz
You can get it like this:
你可以这样得到它:
var suffix = 'comment_like_123456'.match(/\d+/); // 123456
With respect to button:
关于按钮:
$('.comment_like').click(function(){
var suffix = this.id.match(/\d+/); // 123456
});
回答by paislee
In your click handler:
在您的点击处理程序中:
var number = $(this).attr('id').split('_').pop();
回答by ANJYR - KODEXPRESSION
回答by Cory Danielson
var x = 'comment_like_6846511';
var y = '';
for (i = 0; i < x.length; i++)
{
if ("" + parseInt(x[i]) != "NaN") //if the character is a number
y = y + x[i];
}
document.write(y);
回答by meagar
This is a task for plain-old regular expressions, it has nothing to do with jQuery:
这是普通正则表达式的任务,它与 jQuery 无关:
"comment_like_123456".match(/\d+/)
=> ["123456"]
回答by Diodeus - James MacFarlane
jQuery is not a magic bullet. Use Javascript!
jQuery 不是灵丹妙药。使用Javascript!
var temp = "comment_like_123456".split("_")
alert(temp[2])
回答by mgibsonbr
Just get the id and run it through a regex.
只需获取 id 并通过正则表达式运行它。
$(mybutton).click(function() {
var num = parseInt(/^.*\_(\d+)$/.exec(this.id)[1])
});