我有这个脚本,可以很好地添加/删除模糊/专注于文本输入和文本区域的类 - 但是我需要将其绑定(bind)到通过 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 : '');
}
});
});
这不会将事件绑定(bind)到新内容 - 有什么想法吗?
最佳答案
不要使用.bind
,而是使用.on()
:
$( document ).on( 'focus', 'input[type=text], textarea', function() {
// stuff here will be applied to present and *future* elements
});
关于jquery 将焦点/模糊事件绑定(bind)到 AJAX 加载的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4811433/