search

Home  >  Q&A  >  body text

javascript - How to pass parameters in onchange event binding in js?

<input type="file" type="file" accept="image/*" onchange="previewImage" multiple/>

onchangeIf you fill in previewImage, you can get a value in the previewImage function (many people will write it as e). There are files in it. What is this e? ?
If you fill in previewImage('segmentfault') in onchange, and you can only get segmentfault in the previewImage function, where does that e go? ? What should I do if I want to get them at the same time?

Also, what is the difference between previewImage('segmentfault') and previewImage?

When

passes previewImage, isn’t it just a reference? Why is it called directly?

Please recommend a js tutorial or book. Now I only use jq, vue, and various js libraries. . But when I encounter problems, I can't always solve them, which makes me frustrated. . If I want to learn from the basics, please recommend this book

PHPzPHPz2770 days ago804

reply all(3)I'll reply

  • 高洛峰

    高洛峰2017-05-19 10:20:17

    The parameter of previewImage can be this, which refers to the <input> tag.
    Operate files through this.files. For example, this.files.length is the number of files, and this.files[index] points to the corresponding file.
    The parameter of previewImage can be event, which refers to the change event.

    As for adding event handlers, you can
    1. Write the js code directly in quotation marks, such as

    <input type="file" accept="image/*" onchange="alert
    (event.type);" multiple/>
    

    2.onchange = function name, the function is declared in the script. If "previewImage" does not add (), it will not be executed.

    <input type="file" accept="image/*" onchange="previewImage
    (this)" multiple/>
    <script> function previewImage(obj){
                alert(obj.files.length);
            };</script>
    

    3.DOM level 0 event handler

    <input type="file" accept="image/*" multiple/>
    <script> document.getElementsByTagName("input")[0].onchange = function(){
                alert(event.type);
            };</script>
    

    4.DOM level 2 event handler

    <input type="file" accept="image/*"  multiple/>
    <script> document.getElementsByTagName("input")[0].addEventListener("change",function(){
                alert(event.type);
            });</script>`
    或者IE7 8中为`<script> document.getElementsByTagName("input")[0].attachEvent("onchange",function(){
                alert(event.type);
            });</script>
    

    I may have written something wrong. The best way is to practice it yourself.
    The book I read is "JavaScript Advanced Programming" third edition.

    reply
    0
  • 巴扎黑

    巴扎黑2017-05-19 10:20:17

    e表示event
    可以通过this获取相关filesData;
    Recommended "JavaScript Advanced Programming"

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-05-19 10:20:17

    Basic js Recommended Rhino Book--The Authoritative Guide to JavaScript (6th Edition)

    reply
    0
  • Cancelreply