当我运行此代码时:
<!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()
,我发现这很奇怪,因为该函数已定义。
答案 0 :(得分:0)
您声明的函数为“ loadFile”,但在onchange中使用“ LoadFile”。
答案 1 :(得分:0)
JavaScript区分大小写。您应该呼叫loadFile()
中的LoadFile()
而不是onchange
。
这是您的代码:
<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>