jquery get number from id

前端 未结 6 1989
长情又很酷
长情又很酷 2020-12-03 07:56

how can i get the number from a div tag\'s id?

example:

how can i get the 1 and store it in

相关标签:
6条回答
  • 2020-12-03 07:57

    You should get in the habit of using delimiters in your attribute names (ie, button-1, button_1). One of the advantages, of many, is that it makes it easier to extract a number, or some other information, from the field (ie, by splitting the string at '-').

    0 讨论(0)
  • 2020-12-03 08:03
    // replace all non-digits with nothing
    alert($('div').attr("id").replace(/\D/g,''));
    

    If you like, you can just grab the numbers at the end:

    // <div id="_34_foo_555"></div>
    alert($('div').attr("id").match(/\d+$/));
    // alerts "555"
    
    0 讨论(0)
  • 2020-12-03 08:04

    If button is a constant prefix, you can do this:

    var number = parseInt(element.id.match(/^button(\d+)$/)[1], 10);
    
    0 讨论(0)
  • 2020-12-03 08:11

    This is an old question, but I'd like to add the idea of using a data- attribute rather than encoding information in an id:

    window.onload = function() {
      var element = document.getElementById('button1');
      var number = parseInt(element.getAttribute('data-index'), 10);
      console.log(number);
    }
    <button id="button1" data-index="1"></button>

    This way you don't need to go through all of the matching and whatnot.

    0 讨论(0)
  • 2020-12-03 08:21
    var id = $("div").attr('id').replace(/button/, '');
    
    0 讨论(0)
  • 2020-12-03 08:22

    Your "id" values cannot be purely numeric; they need to start with a letter or "_" like an identifier. (Note: that's not true in HTML5 documents.) Once you've got a number in your "id" value like that, you would just use the jQuery attr() function to get the id:

     var theId = parseInt($('div.whatever').attr('id').replace(/[^\d]/g, ''), 10);
    
    0 讨论(0)
提交回复
热议问题