Javascript 如何通过车把为动态元素命名?
每次调用脚本时,我都希望输入字段有一个唯一的名称,并且名称不应该类似。如何做到这一点Javascript 如何通过车把为动态元素命名?,javascript,jquery,json,handlebars.js,Javascript,Jquery,Json,Handlebars.js,每次调用脚本时,我都希望输入字段有一个唯一的名称,并且名称不应该类似。如何做到这一点 <button>Add new field</button> <script type="text/x-handlebars-template" id="file_name"> <input type="file" > </script> <script type="text/javascript"> $('button').o
<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>
添加新字段
$('button')。在('click',function()上{
var template=$('#文件名').html();
var source=handlebar.compile(模板);
$('body').append(source());
});
您可以使用此功能创建唯一的id宽度:
<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>
函数create_uid(){
函数s4(){
返回Math.floor((1+Math.random())*0x10000)
.toString(16)
.子串(1);
}
返回s4()+s4()+'-'+s4()+'-'+s4()+'-''+
s4()+'-'+s4()+s4()+s4()+s4();
}
将唯一id用作hbs模板的变量:
<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>
添加新字段
$('button')。在('click',function()上{
var template=$('#文件名').html();
变量数据={};
data.uid=create_uid();
var source=handlebar.compile(模板)(数据);
$('body').append(source());
});
如果需要:将此函数构建为Handlebar中的助手:是否使用类名?还是使用变量?使用类名或id