2015-12-21 33 views
1

每次調用該腳本時,我都希望爲輸入字段指定一個唯一名稱,並且名稱不應該類似。怎麼能做到這一點?如何通過手柄條爲動態元素賦予唯一的名稱?

<button>Add new field</button> 
<script type="text/x-handlebars-template" id="file_name"> 
    <input type="file" > 
</script> 
<script type="text/javascript"> 
    $('button').on('click',function(){ 
     var template = $('#file-name').html(); 
     var source = Handlebars.compile(template); 
     $('body').append(source());    
    }); 
</script> 
+0

使用類名?或者使用變量? http://handlebarsjs.com/block_helpers.html –

+0

使用類名或ID – xxCodexx

回答

1

您可以創建一個唯一的ID寬度這樣的功能:如果你想

<button>Add new field</button> 
<script type="text/x-handlebars-template" id="file_name"> 
    <input id="{{uid}}" type="file" > 
</script> 
<script type="text/javascript"> 
    $('button').on('click',function(){ 
     var template = $('#file-name').html(); 

     var data = {}; 
     data.uid = create_uid(); 

     var source = Handlebars.compile(template)(data); 

     $('body').append(source());    
    }); 
</script> 

<script> 
    function create_uid() { 
     function s4() { 
     return Math.floor((1 + Math.random()) * 0x10000) 
      .toString(16) 
      .substring(1); 
     } 
     return s4() + s4() + '-' + s4() + '-' + s4() + '-' + 
     s4() + '-' + s4() + s4() + s4(); 
    } 
</script> 

使用獨特的ID作爲變量的HBS模板生成此功能Handlebars幫手:http://handlebarsjs.com/builtin_helpers.html