jQuery:从ID获取号码 [英] Jquery: Getting the number from ID
问题描述
您在另一个问题中提到了此问题: jquery从id获取编号
You mentioned this in another question: jquery get number from id
您应该养成在属性名称(即button-1,button_1)中使用定界符的习惯.许多优点之一是,它使从字段中提取数字或其他信息变得更加容易(例如,通过在'-'处拆分字符串).
You should get in the habit of using delimiters in your attribute names (ie, button-1, button_1). One of the advantages, of many, is that it makes it easier to extract a number, or some other information, from the field (ie, by splitting the string at '-').
如果在属性名称中使用定界符,您将如何提取数字?
How would you extract the number if you are using a delimiter in your attribute names?
谢谢!
推荐答案
-
.attr('id')
可用于检索ID属性. - 然后,使用
.split
函数用分隔符分隔字符串. - 从索引
[1]
获取编号.
.attr('id')
can be used to retrieve the ID attribute.- Then, use the
.split
function to split the string by a separator. - Get the number from index
[1]
.
代码:
var delimiter = '-';
var num = $("element").attr('id').split(delimiter)[1];
// Expected format: <anything 1>-<anything 2>
// Note that <anything 2> is not necessarily a number
以前的方法非常依赖于id格式.一个更可靠的方法是regexp:
The previous method is very dependent on the id format. A more solid method is a regexp:
var num = /\d+/.exec($("element").attr('id')); // Selects all consecutive digits
// Examples:
// button_1 = 1 button2 = 2 1st = 1 button4--5 = 4
要匹配末尾的数字,请使用:
To match the digits at the end, use:
var num = /\d+(?=\D*$)/.exec($("element").attr('id'));
这篇关于jQuery:从ID获取号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!