2011-01-26 10 views
6

Mam ten skrypt, który działa dobrze, aby dodać/usunąć klasę na rozmycie/fokus na wejściach tekstowych i tekstowych - jednak muszę powiązać go z pracą nad treścią dodaną po stronie obciążenie przez AJAX:JQuery wiążą fokus/rozmycie zdarzeń do załadowanych treści AJAX

$(function() { 
    $('input[type=text], textarea').addClass("idleField"); // reset all ## 
    $('input[type=text], textarea').bind("focus", function(event){ 
     $(this).removeClass("idleField").addClass("focusField"); 
     if (this.value == this.defaultValue){ 
     this.value = ''; 
    } 
    if(this.value != this.defaultValue){ 
     this.select(); 
     } 
    }).bind("blur", function(event){ 
    $(this).removeClass("focusField").addClass("idleField"); 
     if ($.trim(this.value) == ''){ 
     this.value = (this.defaultValue ? this.defaultValue : ''); 
    } 
    }); 

}); 

to nie wiąże wydarzeń z nowymi treściami - żadnych pomysłów?

Odpowiedz

10

Zamiast .bind użyć .on():

$(document).on('focus', 'input[type=text], textarea', function() { 
    // stuff here will be applied to present and *future* elements 
}); 
+0

10/10 - i jaką prędkością! - to mój pierwszy post - jak mogę ci przyznać punkty? –

+1

Aby dodać, 'input [type = text]' może być po prostu 'input: text' where: text to [pseudo-selektor] (http://api.jquery.com/category/selectors/). – karim79

+1

Mam nadzieję, że nie masz nic przeciwko, że zmieniłem odpowiedź, aby użyć '.on()' zamiast obecnie nieaktualnych metod. – JJJ

1

Sposób .bind() jest elementów, które obecnie istnieją. Aby dołączyć moduły obsługi zdarzeń do elementów istniejących obecnie w DOM i wszystkich przyszłych elementów, które mogą istnieć, należy użyć metody .live(). Możesz także skorzystać z metody .delegate(), jeśli nie chcesz, aby Twoje zdarzenia pojawiały się na wierzchu DOM.

Ponadto można użyć metody .toggleClass() do przełączania klas elementów w jednym wywołaniu funkcji. Twój kod będzie więc:

$(function() { 
    $('input[type=text], textarea').addClass("idleField"); // reset all ## 
    $('input[type=text], textarea').live("focus", function(event){ 
     $(this).toggleClass("focusField idleField"); 
     if (this.value == this.defaultValue) { 
      this.value = ''; 
     } 
     if (this.value != this.defaultValue) { 
      this.select(); 
     } 
    }).live("blur", function(event){ 
     $(this).toggleClass("focusField idleField"); 
      if ($.trim(this.value) == ''){ 
      this.value = (this.defaultValue ? this.defaultValue : ''); 
     } 
    }); 
});
Powiązane problemy