作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
所以基本上我被困住了。我创建了一个简单的上传图像按钮,可让我预览上传的图像文件。我还创建了一个按钮,用于创建另一个上传图像按钮,该按钮称为“尝试”。我的第一个上传图像按钮可以正确预览图像,但是当我按下“尝试”来创建另一个上传图像按钮并上传另一个图像时,它不会在附加上传图像按钮上预览。我只是想知道如何解决它。以下是完整代码:
function myFunction() {
var x = document.createElement("INPUT");
x.type = "file";
x.id= "file-upload"
x.onchange= "previewFile()";
document.getElementById("wtf").appendChild(x);
var y = document.createElement('IMG');
y.src= "";
y.alt= "Image preview...";
document.getElementById("preview").appendChild(y);
}
function previewFile(){
var preview = document.querySelector('img'); //selects the query named img
var file = document.querySelector('input[type=file]').files[0]; //sames as here
var reader = new FileReader();
reader.onloadend = function () {
preview.src = reader.result;
}
if (file) {
reader.readAsDataURL(file); //reads the data as a URL
} else {
preview.src = "";
}
}
<!DOCTYPE html>
<html>
<body>
<p>Click the button to create a File Upload Button.</p>
<button onclick="myFunction()">Try it</button>
<p id="wtf">
<input id="file-upload" type="file" onchange="previewFile()">
</p>
<p id="preview">
<img src="" height="200" alt="Image preview...">
</p>
</body>
</html>
最佳答案
首先 element.onchange
接受一个函数而不是我更改的字符串,因为您需要使用不同的按钮显示不同的预览,所以您需要一种方法来区分它们。我正在创建一个全局变量 i
来跟踪它,并将其作为参数传递给 previewFile
函数。
这是代码:
var i = 0;
function previewFile(index){
var preview = document.querySelectorAll('img'); //selects the query named img
var file = document.querySelectorAll('input[type=file]')[index].files[0]; //sames as here
var reader = new FileReader();
reader.onloadend = function () {
preview[index].src = reader.result;
}
if (file) {
reader.readAsDataURL(file); //reads the data as a URL
} else {
preview.src = "";
}
}
function myFunction() {
i++;
var y = document.createElement('IMG');
y.src= "";
y.alt= "Image preview...";
y.height = 200;
document.getElementById("preview").appendChild(y);
var x = document.createElement("INPUT");
x.type = "file";
x.id= "file-upload"
x.onchange= function(){previewFile(i)};
document.getElementById("wtf").appendChild(x);
}
<!DOCTYPE html>
<html>
<body>
<p>Click the button to create a File Upload Button.</p>
<button onclick="myFunction()">Try it</button>
<p id="wtf">
<input id="file-upload" type="file" onchange="previewFile(0)">
</p>
<p id="preview">
<img src="" height="200" alt="Image preview...">
</p>
</body>
</html>
关于javascript - Button 创建的上传图像预览代码不会预览图像。 JavaScript/HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51771999/
我有以下正则表达式 /[a-zA-Z0-9_-]/ 当字符串只包含从 a 到z 大小写、数字、_ 和 -。 我的代码有什么问题? 能否请您向我提供一个简短的解释和有关如何修复它的代码示例? //var
我是一名优秀的程序员,十分优秀!