1. 程式人生 > >解決jquery type=hidden change沒觸發

解決jquery type=hidden change沒觸發

一個很蛋疼的問題:頁面上放了一個input type="file",然後給他繫結一個change事件,兩次選擇同一個檔案的時候第二次不會觸發change,呵呵,網上一搜各種答案:

比如:

執行<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
$(function(){
  form.reset(); //清除瀏覽器記錄的上次記錄
  var file;
  $(form).on("change","#file",function(e){
    //輸出選中結果
    console.log(this.value);
    //每次選中都儲存舊元素,並使用新的控制元件替換
    $(this).clone().replaceAll(file=this);
  }).submit(function(){
    //提交時把之前儲存的舊元素替換回去
    $("#file").replaceWith(file);
  });
});
</script>
<form id="form">
  <input type="file" name="file" id="file"><br/>
  <input type="submit" />
</form>

額,貌似有些專案又不能都符合上面的demo,比如我的工程
<input type="file" id="upload"/>
那麼對於這種的解決辦法則是:
if(!!window.ActiveXObject || "ActiveXObject" in window) {    // 此處判斷是否是IE
    $('#upload').replaceWith($('#upload').clone(true));
} else {
    $('#upload').val('');
}

再次去選擇上傳的時候,發現就能正常觸發了!!!奮鬥奮鬥奮鬥