如何使用这个访问div的元素

时间:2018-02-05 14:49:52

标签: javascript jquery html

我想访问这个动态创建的div的元素。这是html

<div id="uploader">
<div class="row uploadDoc">
<div class="col-sm-3">
    <div class="docErr">Please upload valid file</div>
    <!--error-->
    <div class="fileUpload btn btn-orange">
        <img src="https://image.flaticon.com/icons/svg/136/136549.svg" class="icon">
        <span class="upl" id="upload">Upload document</span>
        <input type="file" class="upload up" id="up" onchange="readURL(this);">
    </div>
    <!-- btn-orange -->
</div>
<!-- col-3 -->
<div class="col-sm-8">
    <input type="text" class="form-control" name="" id="document_name" placeholder="Document Name">
</div>
<!--col-8-->
<div class="col-sm-1"><a class="btn-check"><i class="fa fa-times"></i></a></div>
<!-- col-1 -->

这是动态创建的部分

 <div class="row uploadDoc">
<div class="col-sm-3">
    <div class="docErr">Please upload valid file</div>
    <!--error-->
    <div class="fileUpload btn btn-orange"> <img src="https://image.flaticon.com/icons/svg/136/136549.svg" class="icon"><span class="upl" id="upload3">Upload document</span><input type="file" class="upload up" id="up" onchange="readURL(this);"></div>
</div>
<div class="col-sm-8"><input type="text" class="form-control" id="Doc3note" name="" placeholder="Note"></div>
<div class="col-sm-1"><a class="btn-check"><i class="fa fa-times"></i></a></div>

我有一个名为readURL()的文件上传处理程序

 function readURL(input) { }

我想得到的是特定div的id,所以我尝试了这个以及许多其他不成功的方法

   function readURL(input) {  
    console.log($(input).closest('.col-sm-8').find(".form-control").attr('id')); 
  }

我希望我的解释清楚,我希望获得class =&#34; col-sm-8&#34;在文件上传。如何实现这个?

1 个答案:

答案 0 :(得分:0)

传递ID up (uploadFile输入)

执行此操作: $(input).parent().parent().next()

请查看此代码段

&#13;
&#13;
function readURL(input) {
  console.log('Id of Div: ' + $(input).parent().parent().next().attr('id'));
  console.log('Id of form-control input: ' + $(input).parent().parent().next().find(".form-control").attr('id'));
  
}

readURL('#up');
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row uploadDoc">
  <div class="col-sm-3">
    <div class="docErr">Please upload valid file</div>
    <!--error-->
    <div class="fileUpload btn btn-orange"> <img src="https://image.flaticon.com/icons/svg/136/136549.svg" class="icon"><span class="upl" id="upload3">Upload document</span><input type="file" class="upload up" id="up" onchange="readURL(this);"></div>
  </div>
  <div class="col-sm-8" id='div(col-sm-8)'><input type="text" class="form-control" id="Doc3note" name="" placeholder="Note"></div>
  <div class="col-sm-1"><a class="btn-check"><i class="fa fa-times"></i></a></div>
&#13;
&#13;
&#13;

资源