来自以下标记。
<div id="my-div">
<a href="#" id="link-1">Somewhere</a>
<a href="#" id="link-2">Somewhere else</a>
</div>
有哪些选项,使用jQuery选择器和JavaScript来获取ids中的整数?
例如。
$("#my-div a").click(function(){
$(this).id // ... somehow grab n from "link-n"
alert(n);
});
答案 0 :(得分:4)
你可以尝试:
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
}
答案 1 :(得分:2)
$(this).attr('id').replace('link-','')
答案 2 :(得分:2)
只要前面的文本始终保持不变,您就可以使用substring方法获取数字。
$(this).attr('id').substring(5)
答案 3 :(得分:1)
使用正则表达式将是您的最佳选择,例如:
// id contains '1' for id="link-1"
var id = parseInt(this.id.replace(/[^\d]/g, ''), 10);
答案 4 :(得分:1)
我通常做这样的事情:
$("#my-div a").click(function(){
var match;
if (match = $(this).attr('id').match(/link-(\d+)/)) {
var number = parseInt(match[1],10);
alert(number);
}
});
答案 5 :(得分:1)
var id = $(this).attr('id'),
regex = /(\d+)/,
matched = id.match( regex );
if ( matched ) {
alert( matched[1] )
}
答案 6 :(得分:1)
$(this).attr('id').split('-')[1];
答案 7 :(得分:0)
如果您知道所有ID都以“link-”作为前缀,您只需获取id的子字符串:
$("#my-div a").click(function(){
alert(this.id.substr(5));
});
答案 8 :(得分:0)
您可以使用正则表达式解析数字:
var match = /link-(\d+)/.exec($(this).attr('id'));
var num = match[1];
答案 9 :(得分:0)
这应该是最简单的方法:
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')
});