【问题标题】:I want to work with array name in change function我想在更改函数中使用数组名称
【发布时间】:2017-06-30 01:27:55
【问题描述】:

我想检查它的有效图像与否。 我的代码有效图像如下,它的工作很完美,但是当它的图像数组时它不起作用?

$("#file").change(function() {
    var val = $(this).val();
    switch(val.substring(val.lastIndexOf('.') + 1).toLowerCase()){
        case 'gif': case 'jpg': case 'png':
            //alert("an image");
            break;
        default:
            $(this).val('');
            // error message here
            alert("Please Select Valid Image");
            break;
    }

});

它对一个图像的完美工作意味着它在 id 上的工作,但现在我想使用图像数组,那么我该怎么办?有没有可能?

<input id="file" type="file" name="images[]">Enter 8 Images For Batter Product View
<input type="button" id="addmore" value="Add More Image">

在添加更多图像时,它给了我新图像,所以我获取了一个数组,所以我想在数组中检查这个更改函数是否为有效图像? 有可能吗?

谢谢

【问题讨论】:

标签: javascript html arrays arraylist


【解决方案1】:

我只需将 id="file" 更改为 class="file" 即可。

<input class="file" type="file" name="images[]">Enter 8 Images For Batter Product View

<input type="button" id="addmore" value="Add More Image">

<script type="text/javascript">
$(".file").change(function() {
    var val = $(this).val();
    switch(val.substring(val.lastIndexOf('.') + 1).toLowerCase()){
        case 'gif': case 'jpg': case 'png':
            //alert("an image");
            break;
        default:
            $(this).val('');
            // error message here
            alert("Please Select Valid Image");
            break;
    }

});

【讨论】:

  • 只有当它的第一张图片有效然后 ts 在所有标签中添加有效时才第一次工作
【解决方案2】:

file 类型的输入有一个名为files 的属性,它是用户选择的文件的数组。它包含名称和大小等信息。您可以遍历它们并检查用户是否输入了有效图像,如下所示:

$("#file").change(function() {
    var files = this.files; // get the array of files
    var valid = true;

    for(var i = 0; i < files.length && valid; i++) { // while there still files in the array, and valid still true
        var val = files[i].name; // get the current filename

        // check if the file is a valid image or not (if not don't forget to set valid to false)
        switch(val.substring(val.lastIndexOf('.') + 1).toLowerCase()){
            case 'gif': case 'jpg': case 'png':
                // this is a valid image
            break;
            default:
                // this is not a valid image so "valid" should become false
                valid = false;
            break;
        }
    }

    if(!valid) // if valid was set to false insde the array (means an invalid file was selected)
        alert("select valid images");
});

注意:在客户端检查文件是否为图像并不总是有效,用户可以通过更改不是图像的文件的扩展名来绕过您的检查例如,.jpg。阅读更多here

【讨论】:

  • 感谢 replr 先生。如何检查 .jpg 是否有效?先生
  • @Darshan 就如你所愿!只是把你开关而不是我的评论!但正如我所说,仅检查扩展并不总是有效的!
  • @Darshan 我将你的 switch 语句添加到了它应该在的位置!
  • @Darshan 检查此answer 您将不需要上述任何内容。只需设置输入的属性accept!不需要任何验证!
  • 非常感谢先生,但我必须处理这段代码,我没有任何选择,所以我这样做先生
猜你喜欢
  • 2022-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-06
  • 2019-12-08
  • 1970-01-01
  • 2015-08-09
  • 1970-01-01
相关资源
最近更新 更多