簡體   English   中英

如何清除jQuery中的輸入文件字段?

[英]how to clear an input file field in jquery?

在jQuery中,我試圖清除一個字段,但是如果我這樣做,它將引發錯誤。 它的確使該字段為空,但也會引發錯誤。 我該如何解決?

謝謝

HTML

<input name="file" type="file" accept="image/*">

JS

var input = $("#profile-edit-form").find("input[name=file]");
var fileName = input.val();

if(fileName) { // returns true if the string is not empty
    input.replaceWith(input.val('').clone(true));
}

錯誤

NotFoundError: Node was not found                  
-jquery.min.js:3:0

為什么要嘗試clone

只需執行此操作即可清除該字段:

input.val('');

這是一個小提琴來演示:

http://jsfiddle.net/kcbc701c/

編輯:

是的,在較舊的瀏覽器中可能存在上述問題,值得測試,但對我來說,它可以在現代瀏覽器中使用,而您說的另一個選項在Firefox中不起作用...

這是兩者的結合,所以您可以測試: http : //jsfiddle.net/frrc7bLy/

盡管jQuery可能足夠寬容地處理它,但記錄的格式為:

var input = $("#profile-edit-form").find('input[name="file"]');

請注意選擇器中“文件”周圍的引號。

暫無
暫無

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

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