簡體   English   中英

如何將getElementsByClassName,onchange和this.value一起使用?

[英]How to use getElementsByClassName, onchange and this.value together?

我正在嘗試檢查圖像類型的多個文件上載值。 與此HTML:

<input type="file" name="image" id="fileUpload">

而這個js:

document.getElementById('fileUpload').onchange = function () {

    var filename = this.value;
    var a = filename.split(".");
    if( a.length === 1 || ( a[0] === "" && a.length === 2 ) ) {
        return "";
    }   
    var suffix = a.pop().toLowerCase();
    //if( suffix != 'jpg' && suffix != 'jpeg' && suffix != 'png' && suffix != 'gif' && suffix != 'tiff'){
    if (!(suffix in {jpg:'', jpeg:'', png:'', gif:'', tiff:''})){
        document.getElementById('fileUpload').value = "";
        alert('Please select an image.'); 
    }    
};

以上工作正常。 但是有多個輸入:

<input type="file" name="image" id="fileUpload">
<input type="file" name="image" id="fileUpload">
<input type="file" name="image" id="fileUpload">

它只會在第一個起作用。 我嘗試更改為類並使用getElementsByClassName ,但這並沒有做到,也沒有將其包裝在函數中並使用

<input type="file" name="image" id="fileUpload" onchange="checkForImageType()">

您不能有多個具有相同ID的元素,文檔中元素的ID必須是唯一的。

您可以使用類將相似的元素分組,然后使用類選擇器。

由於您已經使用了jQuery標簽

<input type="file" name="image" class="fileUpload">
<input type="file" name="image" class="fileUpload">
<input type="file" name="image" class="fileUpload">

然后

jQuery(function($){
    var regex = /.\.(jpg|jpeg|png|gif|tiff)$/i;
    $('.fileUpload').change(function () {

        var filename = this.value;
        if (!regex.test(filename)) {
            $(this).replaceWith($(this).clone(true, true));// this.value = "" - does not work with IE
            //see http://stackoverflow.com/questions/1043957/clearing-input-type-file-using-jquery
            alert('Please select an image.');
        }
    });
})

演示: 小提琴

由於id必須是唯一的,因此您需要使用class代替input

<input type="file" name="image" id="fileUpload">
<input type="file" name="image" id="fileUpload">
<input type="file" name="image" id="fileUpload">

然后,您可以使用document.getElementsByClassName代替document.getElementById

var fileUpload = document.getElementsByClassName('fileUpload');

for (var i = 0; i < fileUpload.length; i++) {
    fileUpload[i].onchange = function () {
        var filename = this.value;
        var a = filename.split(".");
        if (a.length === 1 || (a[0] === "" && a.length === 2)) {
            return "";
        }
        var suffix = a.pop().toLowerCase();
        //if( suffix != 'jpg' && suffix != 'jpeg' && suffix != 'png' && suffix != 'gif' && suffix != 'tiff'){
        if (!(suffix in {
            jpg: '',
            jpeg: '',
            png: '',
            gif: '',
            tiff: ''
        })) {
            this.value = "";
            alert('Please select an image.');
        }
    }
}

小提琴演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM