问题上获得上传的图像名称与Jquery

Issue On Getting Uploaded Image Name With Jquery

本文关键字:Jquery 图像 问题      更新时间:2023-09-26

我正在尝试获取像这样的上传图像名称

    $(function() {
    $("input[name=file]").on("change", function() {
      if (this.files && this.files[0]) {
      var fimeName = $(this).val(files[0].name);
        console.log(fimeName);
       }
      });
    });
  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" name="file" />

但它不工作,我得到

Uncaught ReferenceError: files is not defined

你能告诉我我在做什么吗?Thansk

您需要在click函数中从事件中获取文件。

    $(function() {
    $("input[name=file]").on("change", function() {
      if (this.files && this.files[0]) {
        //what are you trying to do here?    
        var fileName = this.files[0].name;
        console.log(fileName);
       }
      });
    });
  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" name="file" />

你忘了一个this:

var fimeName = $(this).val(this.files[0].name);

但无论如何,有两件事:你不能显式地设置一个值与val()的输入类型的文件(除了空字符串),和fimeName这里将被分配的this的jQuery匹配集,而不是任何字符串值