jquery bind focus / blur events to AJAX loaded content
I have this script which works fine to add / remove a class on blur / focus on text inputs and textareas - however I need to bind it to also work on content added after page load via AJAX:
$(function() {
$('input[type=text], textarea').addClass("idleField"); // reset all ##
$('input[type=text], textarea').bind("focus", function(开发者_JAVA技巧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 : '');
}
});
});
this is not binding the events to new content - any ideas?
Instead of using .bind
, use .on()
:
$( document ).on( 'focus', 'input[type=text], textarea', function() {
// stuff here will be applied to present and *future* elements
});
The .bind() method is for elements that currently exist. To attach event handlers to elements that currently exist in the DOM and any future elements that might exist you should use the .live() method. You can also use the .delegate() method if you do not want your events to bubble all the way to the top of the DOM.
In addition, you can use the .toggleClass() method to switch classes on your elements in one function call. Thus, your code would be:
$(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 : '');
}
});
});
精彩评论