我只能让用户上传一定数量的图片,所以我试图增加一个变量' j'禁用上传图片按钮前三次。我知道j正在递增,因为我在每个增量的警告框中打印出来。我真的想知道这是怎么回事。如果你有一个更优雅的解决方案,我也很满意。
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
</style>
</head>
<body>
<input id="browse" type="file" onchange="previewFiles()" multiple>
<div id="preview"></div>
<script>
var j = 0;
if (j < 3){
function previewFiles() {
j++;
alert(j);
var preview = document.querySelector('#preview');
var files = document.querySelector('input[type=file]').files;
function readAndPreview(file) {
// Make sure `file.name` matches our extensions criteria
if ( /\.(jpe?g|png|gif)$/i.test(file.name) ) {
var reader = new FileReader();
reader.addEventListener("load", function () {
var image = new Image();
image.height = 100;
image.title = file.name;
image.src = this.result;
preview.appendChild( image );
}, false);
reader.readAsDataURL(file);
}
}
if (files) {
[].forEach.call(files, readAndPreview);
}
}
}
else {
alert("I want to get in here");
document.getElementById("browse").disabled = true;
}
</script>
</body>
答案 0 :(得分:1)
if
块在函数之外,因此在调用previewFiles
时,不会执行if
块。试试这个:
var j = 0;
function previewFiles() {
if (j < 3) {
j++;
alert(j);
var preview = document.querySelector('#preview');
var files = document.querySelector('input[type=file]').files;
function readAndPreview(file) {
// Make sure `file.name` matches our extensions criteria
if (/\.(jpe?g|png|gif)$/i.test(file.name)) {
var reader = new FileReader();
reader.addEventListener("load", function() {
var image = new Image();
image.height = 100;
image.title = file.name;
image.src = this.result;
preview.appendChild(image);
}, false);
reader.readAsDataURL(file);
}
}
if (files) {
[].forEach.call(files, readAndPreview);
}
} else {
alert("I want to get in here");
document.getElementById("browse").disabled = true;
}
}
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
</style>
</head>
<body>
<input id="browse" type="file" onchange="previewFiles()" multiple>
<div id="preview"></div>
</body>