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

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

From the following markup.


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

    I usually do something like this:

    $("#my-div a").click(function(){
        var match;
        if (match = $(this).attr('id').match(/link-(\d+)/)) {
          var number = parseInt(match[1],10);
          alert(number);
        }
    });
    
    0 讨论(0)
  • 2021-01-18 21:33

    This should be the simplest way:

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

    It returns any digits from the ID attribute as a number (*1 does the conversion, similar to parseInt). In your example:

    $("#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')
    });
    
    0 讨论(0)
  • 2021-01-18 21:37

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

    0 讨论(0)
  • 2021-01-18 21:42
    $(this).attr('id').split('-')[1];
    
    0 讨论(0)
  • 2021-01-18 21:47
    var id = $(this).attr('id'),
        regex = /(\d+)/,
        matched = id.match( regex );
    
    if ( matched ) {
        alert( matched[1] )
    }
    
    0 讨论(0)
  • 2021-01-18 21:47

    You can use a regular expression to parse out the number:

    var match = /link-(\d+)/.exec($(this).attr('id'));
    var num = match[1];
    
    0 讨论(0)
提交回复
热议问题