search
HomeWeb Front-endJS TutorialDetailed explanation of the steps to upload and echo multiple images using input tags and jquery

This time I will give you a detailed explanation of the steps to use the input tag and jquery to implement the upload and echo function of multiple images, and use the input tag and jquery to implement the upload and echo function of multiple images What are the precautions? The following is a practical case, let’s take a look.

Rendering

Let’s make a demo like this from scratch

The first step:

Let’s first Let’s improve our page. The default input-file tag is very ugly. Let’s beautify it. If you don’t know it, you can use Baidu. Just put a box outside, set the opacity of the input to 0, and then design the outside box into the style we like. That’s it, I just did it casually.

Approximate style

Let’s put the source code and only talk about the effect. Anyone who doesn’t put the source code is just a rogue

This is the body

  <p>
    <input>
  </p>

This is the style of css

.uploadImgBtn {
    width: 100px;
    height: 100px;
    cursor: pointer;
    position: relative;
    background: url("img/plus.png") no-repeat;
    -webkit-background-size: cover;
    background-size: cover;
  }
  .uploadImgBtn .uploadImg {
    position: absolute;
    right: 0;
    top:0;
    width: 100%;
    height: 100%;
    opacity: 0;
    cursor: pointer;
  }
  //这是一个用做回显的盒子的样式
  .pic{
    width: 100px;
    height: 100px;
  }
  .pic img {
    width: 100%;
    height: 100%;
  }

The amount of code is not much. Next we will analyze how to echo the image; I know there are two ways, one is to upload it to The server returns the url of the image, and then renders it on the page; the other is to use the FileReader object of h5 to directly preview the image locally, and then upload it to the server after the user confirms it.

We are using the second form. Now that we know the idea, let’s start programming.

<script>
  $(document).ready(function(){
    //为外面的盒子绑定一个点击事件
    $("#uploadImgBtn").click(function(){
      /*
      1、先获取input标签
      2、给input标签绑定change事件
      3、把图片回显
       */
//      1、先回去input标签
      var $input = $("#file");
//      2、给input标签绑定change事件
      $input.on("change" , function(){
        //补充说明:因为我们给input标签设置multiple属性,因此一次可以上传多个文件
        //获取选择图片的个数
        var files = this.files;
        var length = files.length;
        console.log("选择了"+length+"张图片");
        //3、回显
        for( var i = 0 ; i < length ; i++ ){
          var fr = new FileReader(),
            p = document.createElement("p"),
            img = document.createElement("img");
          p.className = &#39;pic&#39;;
          fr.onload = function(e){
            console.log("回显了图片")
            img.src = this.result;
            p.appendChild(img)
            document.body.appendChild(p);
          }
          fr.readAsDataURL(files[i]);//读取文件
        }
      })
    })
  })
</script>

The idea of ​​​​the code can also be said to be very simple. First bind the click event to the outside box. Then get the input tag, bind the change event to the input tag, and then use a for loop to echo the obtained data. There is an asynchronous event onload in the for loop that is used to render the image. Let's take a look at the rendering

Rendering

We selected three pictures, but one was displayed. In other words, we created three p and img in the for loop, but only one was displayed. There must be something fishy in this picture.

Let’s analyze it carefully. As I said before, there is an asynchronous event in the echoed for loop. Since it is asynchronous, it may be that the onload event is executed after the for loop is executed to make the subscript we set. The i value is inconsistent with the expected result; then how do we solve it? If we can form a function scope, in which a picture is echoed each time, I think we can solve it. Let's try it. Our front end can use jquery's each solution, which comes with callback function, forming a function scope. Let’s take a look at the code

<script>
  $(document).ready(function(){
    //为外面的盒子绑定一个点击事件
    $("#uploadImgBtn").click(function(){
      /*
      1、先获取input标签
      2、给input标签绑定change事件
      3、把图片回显
       */
//      1、先回去input标签
      var $input = $("#file");
//      2、给input标签绑定change事件
      $input.on("change" , function(){
        //补充说明:因为我们给input标签设置multiple属性,因此一次可以上传多个文件
        //获取选择图片的个数
        var files = this.files;
        var length = files.length;
        console.log("选择了"+length+"张图片");
        //3、回显
        $.each(files,function(key,value){
          //每次都只会遍历一个图片数据
          var p = document.createElement("p"),
            img = document.createElement("img");
          p.className = "pic";
          var fr = new FileReader();
          fr.onload = function(){
            img.src=this.result;
            p.appendChild(img);
            document.body.appendChild(p);
          }
          fr.readAsDataURL(value);
        })
      })
    })
  })
</script>

and see the running effect

Rendering chart

This time we achieved our expected effect. Is this the end? It’s definitely not. When we click the upload image button again, the last result will definitely be overwritten. So when we run business, this is definitely not what we want to see. So what do we do? To solve this problem, we must use multiple input tags. Then how can we ensure that when we click, it will be the newly added input tag? My solution is this, we put the id of the last input tag Clear the attribute and add this attribute to our newly generated input tag. Because we bind the event through the id, we can bind the event to our newly generated input tag, and the original input tag is gone. id attribute without being selected, let’s look at the code

<script>
  $(document).ready(function(){
    //为外面的盒子绑定一个点击事件
    $("#uploadImgBtn").click(function(){
      /*
      1、先获取input标签
      2、给input标签绑定change事件
      3、把图片回显
       */
//      1、先回去input标签
      var $input = $("#file");
      console.log($input)
//      2、给input标签绑定change事件
      $input.on("change" , function(){
        console.log(this)
        //补充说明:因为我们给input标签设置multiple属性,因此一次可以上传多个文件
        //获取选择图片的个数
        var files = this.files;
        var length = files.length;
        console.log("选择了"+length+"张图片");
        //3、回显
        $.each(files,function(key,value){
          //每次都只会遍历一个图片数据
          var p = document.createElement("p"),
            img = document.createElement("img");
          p.className = "pic";
          var fr = new FileReader();
          fr.onload = function(){
            img.src=this.result;
            p.appendChild(img);
            document.body.appendChild(p);
          }
          fr.readAsDataURL(value);
        })
      })
      //4、我们把当前input标签的id属性remove
      $input.removeAttr("id");
      //我们做个标记,再class中再添加一个类名就叫test
      var newInput = &#39;<input class="uploadImg test" type="file" name="file" multiple id="file">&#39;;
      $(this).append($(newInput));
    })
  })
</script>

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website !

Recommended reading:

How to use Vue to make Amap and build a real-time bus application

How to use seajs in require Writing convention

The above is the detailed content of Detailed explanation of the steps to upload and echo multiple images using input tags and jquery. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
jquery实现多少秒后隐藏图片jquery实现多少秒后隐藏图片Apr 20, 2022 pm 05:33 PM

实现方法:1、用“$("img").delay(毫秒数).fadeOut()”语句,delay()设置延迟秒数;2、用“setTimeout(function(){ $("img").hide(); },毫秒值);”语句,通过定时器来延迟。

jquery怎么修改min-height样式jquery怎么修改min-height样式Apr 20, 2022 pm 12:19 PM

修改方法:1、用css()设置新样式,语法“$(元素).css("min-height","新值")”;2、用attr(),通过设置style属性来添加新样式,语法“$(元素).attr("style","min-height:新值")”。

axios与jquery的区别是什么axios与jquery的区别是什么Apr 20, 2022 pm 06:18 PM

区别:1、axios是一个异步请求框架,用于封装底层的XMLHttpRequest,而jquery是一个JavaScript库,只是顺便封装了dom操作;2、axios是基于承诺对象的,可以用承诺对象中的方法,而jquery不基于承诺对象。

jquery怎么在body中增加元素jquery怎么在body中增加元素Apr 22, 2022 am 11:13 AM

增加元素的方法:1、用append(),语法“$("body").append(新元素)”,可向body内部的末尾处增加元素;2、用prepend(),语法“$("body").prepend(新元素)”,可向body内部的开始处增加元素。

jquery中apply()方法怎么用jquery中apply()方法怎么用Apr 24, 2022 pm 05:35 PM

在jquery中,apply()方法用于改变this指向,使用另一个对象替换当前对象,是应用某一对象的一个方法,语法为“apply(thisobj,[argarray])”;参数argarray表示的是以数组的形式进行传递。

jquery怎么删除div内所有子元素jquery怎么删除div内所有子元素Apr 21, 2022 pm 07:08 PM

删除方法:1、用empty(),语法“$("div").empty();”,可删除所有子节点和内容;2、用children()和remove(),语法“$("div").children().remove();”,只删除子元素,不删除内容。

jquery怎么去掉只读属性jquery怎么去掉只读属性Apr 20, 2022 pm 07:55 PM

去掉方法:1、用“$(selector).removeAttr("readonly")”语句删除readonly属性;2、用“$(selector).attr("readonly",false)”将readonly属性的值设置为false。

jquery on()有几个参数jquery on()有几个参数Apr 21, 2022 am 11:29 AM

on()方法有4个参数:1、第一个参数不可省略,规定要从被选元素添加的一个或多个事件或命名空间;2、第二个参数可省略,规定元素的事件处理程序;3、第三个参数可省略,规定传递到函数的额外数据;4、第四个参数可省略,规定当事件发生时运行的函数。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!