开发者问题收集

未捕获的 ReferenceError:LoadFile 未定义错误

2020-04-23
1097

当我运行此代码时:

<!DOCTYPE html>
<html>
  <head>
    <title>Upload Button</title>
  </head>
  <body>
    <input type="file" accept="image/*" style="display:none" onchange="LoadFile(event)" id="file" name="image"/>
    <label for="file" style="cursor:pointer">Upload image</label>
    <br>
    <img id="output" style="width:200px; height:200px;"/>
    <script>
      var loadFile = function(event) {
	    var image = document.getElementById("output");
		image.src = URL.createObjectURL(event.target.files[0]);
	  };
	</script>
  </body>
</html>

浏览器抛出此错误:

Uncaught ReferenceError: LoadFile is not defined at HTMLInputElement.onchange (tp1.html:7)

它说函数 LoadFile() 未定义,我发现这很奇怪,因为该函数已定义。

2个回答

JavaScript 区分大小写。您应该在 onchange 中调用 loadFile() ,而不是 LoadFile()

这是您的代码:

<html>
  <head>
    <title>Upload Button</title>
  </head>
  <body>
    <input type="file" accept="image/*" style="display:none;" onchange="loadFile(event)" id="file" name="image"/>
    <label for="file" style="cursor:pointer">Upload image</label>
    <br>
    <img id="output" style="width:200px; height:200px;"/>
    <script>
            var loadFile = function(event) {
            var image = document.getElementById("output");
            image.src = URL.createObjectURL(event.target.files[0]);
            };
        </script>
  </body>
</html>

或者将 loadFile() 更改为 LaodFile()

<html>
  <head>
    <title>Upload Button</title>
  </head>
  <body>
    <input type="file" accept="image/*" style="display:none;" onchange="LoadFile(event)" id="file" name="image"/>
    <label for="file" style="cursor:pointer">Upload image</label>
    <br>
    <img id="output" style="width:200px; height:200px;"/>
    <script>
            var LoadFile = function(event) {
            var image = document.getElementById("output");
            image.src = URL.createObjectURL(event.target.files[0]);
            };
        </script>
  </body>
</html>
MARSHMALLOW
2020-04-23

您声明的函数是“loadFile”,但您在 onchange 中使用了“LoadFile”。

tanpopo
2020-04-23