jQuery清除表單資料程式碼例項

admin發表於2017-03-09

清除表單中的資料最簡單的方法,就是點選重置按鈕實現清空效果,但是在實際應用中可能需要根據程式碼的具體執行情況來清除表單中的資料,下面就分享一段能夠實現此功能的jQuery程式碼。

[JavaScript] 純文字檢視 複製程式碼
function clearForm(form) {
  $(':input', form).each(function() {
    var type = this.type;
    var tag = this.tagName.toLowerCase();
    if (type == 'text' || type == 'password' || tag == 'textarea')
      this.value = "";
    else if (type == 'checkbox' || type == 'radio')
      this.checked = false;
    else if (tag == 'select')
      this.selectedIndex = -1;
  });
};

以上程式碼實現了我們的要求,下面對程式碼做一下簡單註釋。

一.程式碼註釋:

1.function clearForm(form) {},引數為表單物件。

2.$(':input', form).each(function() {}),遍歷表單中的每一個input元素。

3.var type = this.type,獲取input元素的type屬性值。

4.var tag = this.tagName.toLowerCase(),獲取標籤名稱並且將標籤名轉換為小寫。

5.if (type == 'text' || type == 'password' || tag == 'textarea') this.value = "",如果input元素的型別為文字或者密碼框或者標籤為多行文字框,就將value屬性值設定為空。

6.else if (type == 'checkbox' || type == 'radio') this.checked = false,如果為單選框或者核取方塊,那麼就取消選中。

7.else if (tag == 'select') this.selectedIndex = -1,如果是select下拉選單,就取消選中項。

相關文章