Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/405.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 Jquery基于id克隆带有标签的输入_Javascript_Jquery - Fatal编程技术网

Javascript Jquery基于id克隆带有标签的输入

Javascript Jquery基于id克隆带有标签的输入,javascript,jquery,Javascript,Jquery,您好,我有一个输入文件,我喜欢输入样式,没有标签和ID我无法获得它 我花了几个小时解决了这个问题,我只是想知道有没有更好的解决办法 $("body").on("click",".btn-success",function(){ $('.clone .custom-file-label').attr('class', 'custom-file-label') var html = $(".clone").html();

您好,我有一个输入文件,我喜欢输入样式,没有标签和ID我无法获得它

我花了几个小时解决了这个问题,我只是想知道有没有更好的解决办法

          $("body").on("click",".btn-success",function(){
          $('.clone .custom-file-label').attr('class', 'custom-file-label')
          var html = $(".clone").html();
          var NewN = html.match(/id="(.*?)"/)[1];
          $('#' + NewN).attr("id", parseInt(NewN) + 1);
          $('.clone .custom-file-label').attr("for", parseInt(NewN) + 1);
          $(".increment").after(html);
      });

      $("body").on("click",".btn-danger",function(){
          $(this).parents(".control-group").remove();
      });

  • 我肯定会将逻辑与DOM分离(例如,不依赖DOM作为ID)
  • 将模板放在JS脚本中,这样我就可以很容易地修改它使用的外观和逻辑
  • 将减少对动态创建的元素(例如,不是“主体”而是“容器”)上的单击作出反应的范围
  • 我会将所有CSS样式提取到单独的CSS
  • 这段代码中的所有内容:

    //跟踪ID
    设id=1
    //创建要追加的项
    const addFileInput=(id)=>{
    //正在创建将返回的基本节点
    const node=document.createElement('div')
    //在基本节点上设置类
    node.classList.add('custom-file','mb-3')
    //创建节点的innerHTML
    node.innerHTML=`
    ${id==1?'+':'-'}
    选择文件`
    //返回节点
    返回节点
    }
    //追加第一个输入字段(类型:node)
    const container=document.getElementById('field-container'))
    container.appendChild(addFileInput(id))
    //onClick函数
    $(文档).ready(函数(){
    $(container).on(“click”,“.btn success”,函数(){
    //在追加之前增加ID
    container.appendChild(addFileInput(++id))
    });
    $(容器).on(“单击“,”.btn danger”,函数(){
    //移除精确的元素
    $(this.parents('.custom file').remove();
    });
    });
    
    .control group.custom文件{
    宽度:300px;
    显示器:flex;
    }