2017-11-11 166 views
1

我有輸入其中是標籤(如佔位符),如果我寫入輸入然後標籤獲取class =「active」。 (This works)jquery如果值不爲空添加活動類

但是,如果它已經value =「測試」,那麼它必須自動標記class =「active」。

我的代碼:

$('.data').find('input, textarea').on('keyup blur focus', function (e) { 
    var $this = $(this), 
     label = $this.prev('label'); 

    if ($this.val() === '') { 
     label.removeClass('active highlight'); 
    } else { 
     label.addClass('active highlight'); 
    } 

    if ($this.val() === '') { 
     label.removeClass('active highlight'); 
    } else { 
     label.removeClass('highlight'); 
    } 

    if ($this.val() === '') { 
     label.removeClass('highlight'); 
    } else if ($this.val() !== '') { 
     label.addClass('highlight'); 
    } 
}); 

與此代碼的工作,只有KEYUP。

$('.data').find('input, textarea').on('keyup blur focus', function (e) { 
    var $this = $(this), 
     label = $this.prev('label'); 

    if (e.type === 'keyup') { 
     if ($this.val() === '') { 
      label.removeClass('active highlight'); 
     } else { 
      label.addClass('active highlight'); 
     } 
    } else if (e.type === 'blur') { 
     if ($this.val() === '') { 
      label.removeClass('active highlight'); 
     } else { 
      label.removeClass('highlight'); 
     } 
    } else if (e.type === 'focus') { 
     if ($this.val() === '') { 
      label.removeClass('highlight'); 
     } else if ($this.val() !== '') { 
      label.addClass('highlight'); 
     } 
    } 
}); 

目前,如果輸入值=「測試」,如果我點擊輸入,然後它給類活躍,但我需要它自動添加。

回答

1

頁面加載後立即觸發keyup事件,自動添加active類,如下所示。

$('.data').find('input, textarea').on('keyup blur focus', function (e) { 
    //your code 
}).keyup(); 
1

如果我點擊輸入,然後它給類活躍,但我需要它自動添加。

這很簡單,只是激發的事件之一,你會留意:

$('.data').find('input,textarea').trigger('keyup') 

同時,你的功能是不必要的重複;沒有必要單獨處理你正在觀看的三個事件中的每一個,因爲他們都在做同樣的事情。你可以減少到

$('.data').find('input, textarea').on('keyup blur focus', function (e) { 
    var $this = $(this), 
     label = $this.prev('label'); 
    if ($this.val() === '') { 
    label.removeClass('active highlight'); 
    } else { 
    label.addClass('active highlight'); 
    } 
}).trigger('keyup'); 

...或更好,但只使用change事件相反,因爲這是最相關的你想要做什麼。