Jquery最接近而find没有'似乎不起作用

Jquery closest and find doesn't seem to work

本文关键字:不起作用 最接近 find 没有 Jquery      更新时间:2023-09-26

这些是我的代码。我无法使jquery代码正常工作。

HTML:

<div class="col-lg-6 col-md-6 col-sm-6"> 
  <input name="hImage" class="form-control"  type="file" id="headerImage" required> 
  <img src="" id="img_url" alt="your image" class="img-responsive"> 
</div>

JQUERY:

function readURL(e){
    if (this.files && this.files[0]){
        var reader = new FileReader();
        $(reader).load(function(e) {
            imagePrev = e.target.result;
            var imgElement = $(this).closest('div').find('img');
            imgElement.attr('src', imagePrev);
        });
        reader.readAsDataURL(this.files[0]);   
};

我用这个代码触发功能:

$("#headerImage").change(readURL);

CCD_ 1是一个base64数据。这很有效,因为当我尝试时

$("#img_url").attr('src', imagePrev);

图像被加载。

但我想使用最接近的、.find或.sbrothers或任何必要的代码,这样我就可以找到最接近的img标记并替换它的src属性。

问题在于this变量,一旦执行进入$(reader).load()内部,this变量的值就会更改。

使用以下内容。

function readURL(e){
    $this = $(this);
    if (this.files && this.files[0]){
        var reader = new FileReader();
        $(reader).load(function(e) {
            imagePrev = e.target.result;
            var imgElement = $this.siblings('img');
            imgElement.attr('src', imagePrev);
        });
        reader.readAsDataURL($this[0].files[0]);  
    } 
};