jquery将焦点/模糊事件绑定到AJAX加载的内容

Q S*_*dio 6 ajax jquery bind focus blur

我有这个脚本可以正常添加/删除模糊/焦点文本输入和textareas上的类 - 但是我需要将它绑定到也可以处理通过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 : '');
   }
  });

 });
Run Code Online (Sandbox Code Playgroud)

这不是将事件绑定到新内容 - 任何想法?

kar*_*m79 10

而不是使用.bind,使用.on():

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

  • 我希望您不介意我更改了使用 `.on()` 而不是现在已弃用的方法的答案。 (2认同)