Automatically generating unique DOM ids?

前端 未结 4 2195
别那么骄傲
别那么骄傲 2020-12-18 22:33

When coding with JS and the DOM I find myself constantly needing to generate ids (or names) that have no purpose other than to group DOM elements together (or r

相关标签:
4条回答
  • 2020-12-18 22:39

    Example of working with radio labels without ID:

    <div class="button-group" name="sys">
      <input type="radio" value="lnx" name="radio1"> <label> Linux   </label> <br>
      <input type="radio" value="osx"  name="radio1"> <label> OS X    </label> <br>
      <input type="radio" value="win"  name="radio1"> <label> Windows </label>
    </div>
    
    
       <div class="content">
           <div>Show me when 1st radio checked</div> 
           <div>Show me when 2nd radio checked</div> 
           <div>Show me when 3rdd radio checked</div>
       </div>
    

    JS

    $('.button-group[name=sys] :radio').change(function(){
        $(this).parent().find('label').removeClass('active');
         $(this).next().addClass('active');
    
          /* index radios vs content*/
    
          var radioIndex=$('.button-group[name=sys] :radio').index(this);
           /* hide all the content div, show one that matches radio index*/
           $('.content div').hide().eq(radioIndex).show();
    })
    
    0 讨论(0)
  • 2020-12-18 22:48

    A common approach - for example in ajax calls - is to use new Date().getTime().

    If you are worried that you might output the same id twice, you can always add a validation step:

    do {uniqueID=new Date().getTime();} while (document.getElementById(uniqueID));
    
    0 讨论(0)
  • 2020-12-18 22:51

    I agree with some of the commenters that there are probably better ways to do this, but a simple implementation of unique_id() you could use would be:

    return Math.random().toString(36);
    
    0 讨论(0)
  • 2020-12-18 23:02

    One approach which I've used is

    (function(){
        var counter = 0;
        window.uniqueId = function(){
            return 'myid-' + counter++
        }
    });
    

    then

    $('.button-group').each(function (i, e) {
      var name = uniqueId();
      $(e).find(':radio').each(function (j, f) {
        var id = uniqueId();
        $(f).attr('name', name)
            .attr('id', id)
          .next()
            .attr('for', id);
      })
    });
    
    0 讨论(0)
提交回复
热议问题