JavaScript/jQuery - grabbing an integer from an element's id

前端 未结 10 537
青春惊慌失措
青春惊慌失措 2021-01-18 20:55

From the following markup.


                      
相关标签:
10条回答
  • 2021-01-18 21:52

    You could try:

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

    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.

    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);
    

    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
    }
    
    0 讨论(0)
  • As long as the preceding text always remains the same you can just use the substring method to get the number.

    $(this).attr('id').substring(5)
    
    0 讨论(0)
  • 2021-01-18 21:56

    If you know that all your ids are prefixed by "link-", you can simply get the substring of the id:

    $("#my-div a").click(function(){
       alert(this.id.substr(5));
    });
    
    0 讨论(0)
  • 2021-01-18 21:57

    Using a regex would be your best option, for instance:

    // id contains '1' for id="link-1"
    var id = parseInt(this.id.replace(/[^\d]/g, ''), 10);
    
    0 讨论(0)
提交回复
热议问题