我的页面上有一个按钮,其中包含类comment_like和ID,comment_like_123456但最后的数字是可变的; 可能是1到1000000.
单击此按钮时,我需要获取结束编号,以便我可以在具有相同后缀的其他元素上运行任务.
有没有一种简单的方法可以在jQuery中获取这个数字?
$('.comment_like').click(function() {
var element_id = $(this).attr('id');
// grab number from element ID
// do stuff with that number
});
Run Code Online (Sandbox Code Playgroud)
Sar*_*raz 98
你可以这样得到它:
var suffix = 'comment_like_123456'.match(/\d+/); // 123456
Run Code Online (Sandbox Code Playgroud)
关于按钮:
$('.comment_like').click(function(){
var suffix = this.id.match(/\d+/); // 123456
});
Run Code Online (Sandbox Code Playgroud)
pai*_*lee 14
在您的点击处理程序中
var number = $(this).attr('id').split('_').pop();
Run Code Online (Sandbox Code Playgroud)
Anj*_*jyr 12
你可以试试这个。它将从任何类型的字符串中提取所有数字。
var suffix = 'comment_like_6846511';
alert(suffix.replace(/[^0-9]/g,''));
Run Code Online (Sandbox Code Playgroud)