使用 $(this).val( " " ) 重置输入文件,不适用于 IE8



可能的重复项:
IE 9 jQuery未设置输入值

如果输入字段符合某些条件,我想使用 $(this).val(""); 重置输入字段:

$(".checkimgextension").on("change", function () {
var file = $(this).val();
if (some conditions){
  alert("wrong:...");
  $(this).val("");
}   

在 Firefox 中,该字段设置为 "" ,但在 IE 中,该字段不会按预期更改。是否正在使用正确的功能.val("")

参考:IE 9 jQuery未设置输入值

$("input[type='file']").replaceWith($("input[type='file']").clone(true));

所以在你的情况下:

$(this).replaceWith($(this).clone(true));

而不是$(this).val("");行。

更新:

为了利用允许您修改input:file元素的浏览器,我将使用如下内容:

$(".checkimgextension").on("change", function () {
    var $this = $(this);
    if (some conditions) {
        alert("wrong:...");
        $this.val("");
        var new_val = $this.val();
        if (new_val !== "") {
            $this.replaceWith($this.clone(true));
        }
    }
});

这样,它首先尝试仅将值设置为空,如果不成功,请使用 replaceWith 方法。

最新更新