Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/378.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用addEventListener(非jquery)创建元素唯一id_Javascript_Loops_Click_Addeventlistener - Fatal编程技术网

Javascript 使用addEventListener(非jquery)创建元素唯一id

Javascript 使用addEventListener(非jquery)创建元素唯一id,javascript,loops,click,addeventlistener,Javascript,Loops,Click,Addeventlistener,我有这个: var divProducthere= document.getElementById('divProducthere'); //div var productbutton = document.getElementById('productbutton'); // button productbutton.addEventListener('click',prodElement); function prodElement(){ for (var i

我有这个:

var divProducthere= document.getElementById('divProducthere'); //div 
var productbutton = document.getElementById('productbutton'); // button

  productbutton.addEventListener('click',prodElement);

   function prodElement(){
       for (var i = 0; i < 9; i++) {
        var selectProduct = document.createElement('select');
        selectProduct.id = 'r'+i;
        divProducthere.appendChild(selectProduct);

}
var divProducthere=document.getElementById('divProducthere')//div
var productbutton=document.getElementById('productbutton');//按钮
productbutton.addEventListener('click',prodElement);
函数prodElement(){
对于(变量i=0;i<9;i++){
var selectProduct=document.createElement('select');
选择product.id='r'+i;
divProducthere.appendChild(选择产品);
}

这对我不起作用,因为我只需要通过单击事件逐个创建元素,但为每个创建的元素分配唯一的id

您可以创建一个唯一的id,如下所示:

函数uniqId(长度=6){
return(Math.random().toString(36)+Math.random().toString(36)).substr(2,长度);
}
for(设i=0;i<10;i++){
log(uniqId(parseInt(Math.max(2,Math.random()*10)))

}
将计数器放入全局变量中

var select_counter = 0;
function prodElement() {
    select_counter++;
    var selectProduct = document.createElement('select');
    selectProduct.id = 'r'+select_counter;
    divProducthere.appendChild(selectProduct);
}

为什么你需要一个ID?因为我每次点击按钮都需要创建一个元素,但为什么这些元素需要ID?一旦添加了动态元素,我需要识别它们以进行提交。如果你在任何数据结构中存储对这些元素的引用,这可能比每次按ID查找它们更有效。
doc然后,createElement将精确返回您需要的内容。