使用$(this).val(“”)重置输入文件不能与IE8一起使用

时间:2012-12-06 14:11:38

标签: javascript jquery internet-explorer

  

可能重复:
  IE 9 jQuery not setting input value

如果输入字段与$(this).val("");匹配某些条件,我想重置输入字段:

$(".checkimgextension").on("change", function () {

var file = $(this).val();

if (some conditions){
  alert("wrong:...");
  $(this).val("");
}   

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

1 个答案:

答案 0 :(得分:8)

请参阅:IE 9 jQuery not setting input value

$("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方法。