JavaScript / jQuery – 从元素的id中获取一个整数

从以下标记。

 

有什么选择,使用jQuery选择器和JavaScript来获取ID中的整数?

例如。

 $("#my-div a").click(function(){ $(this).id // ... somehow grab n from "link-n" alert(n); }); 

你可以尝试:

 var n = $(this).attr('id').match(/link-(\d+)/)[1]; 

这将获取id属性,匹配模式link-(\d+) (表示link-后跟一个或多个数字),然后提取第一个子表达式匹配(括号中的部分\d+ ),这应该是你正在寻找的号码。

如果你需要使用n作为整数而不是字符串,你应该使用parseInt ,确保指定基数10:

 var n = parseInt($(this).attr('id').match(/link-(\d+)/)[1], 10); 

如果您的id属性不能保证以link-后跟一个或多个数字开头,并且您希望捕获此情况而不是抛出错误,则应检查match的返回值:

 var match = $(this).attr('id').match(/link-(\d+)/); if (match) { var n = parseInt(match[1], 10); alert(n); } else { // do something else if they don't match } 

$(this).attr('id').replace('link-','')

只要前面的文本始终保持不变,您就可以使用substring方法来获取数字。

 $(this).attr('id').substring(5) 
 $(this).attr('id').split('-')[1]; 
 var id = $(this).attr('id'), regex = /(\d+)/, matched = id.match( regex ); if ( matched ) { alert( matched[1] ) } 

我通常做这样的事情:

 $("#my-div a").click(function(){ var match; if (match = $(this).attr('id').match(/link-(\d+)/)) { var number = parseInt(match[1],10); alert(number); } }); 

使用正则表达式将是您的最佳选择,例如:

 // id contains '1' for id="link-1" var id = parseInt(this.id.replace(/[^\d]/g, ''), 10); 

如果您知道所有id都以“link-”作为前缀,则只需获取id的子字符串:

 $("#my-div a").click(function(){ alert(this.id.substr(5)); }); 

这应该是最简单的方法:

 var id = this.id.replace(/[^\d]/g,'')*1; 

它返回ID属性中的任何数字作为number*1进行转换,类似于parseInt )。 在你的例子中:

 $("#my-div a").click(function(){ var n = this.id.replace(/[^\d]/g,'')*1; alert(n); // alerts any number in the ID attribute alert(typeof n) // alerts 'number' (not 'string') }); 

您可以使用正则表达式来解析数字:

 var match = /link-(\d+)/.exec($(this).attr('id')); var num = match[1];