JavaScript/jQuery-从元素的ID中获取整数 [英] JavaScript/jQuery - grabbing an integer from an element's id

查看:113
本文介绍了JavaScript/jQuery-从元素的ID中获取整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过以下标记.

<div id="my-div">
    <a href="#" id="link-1">Somewhere</a>
    <a href="#" id="link-2">Somewhere else</a>
</div>

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

What are some options, using jQuery selectors and JavaScript for grabbing the integer in the ids?

例如.

$("#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+),应该是您要寻找的号码.

This fetches the id attribute, matches against the pattern link-(\d+) (which means link- followed by one or more digits), and then extracts the first subexpression match (the part in the parentheses \d+), which should be the number you are looking for.

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

If you need to work with n as an integer instead of a string, you should should use parseInt, making sure to specify base 10:

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

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

If your id attributes are not guaranteed to begin with link- followed by one or more digits, and you would like to catch this case instead of throwing an error, you should check the return value of 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
}

这篇关于JavaScript/jQuery-从元素的ID中获取整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆