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

标签 jquery ajax focus bind blur

我有这个脚本,可以很好地添加/删除模糊/专注于文本输入和文本区域的类 - 但是我需要将其绑定(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/

相关文章:

jquery - ASP MVC3 应用程序在 IE8 中引发 JScript 错误,但在 FireFox 4 中正常工作

在 foreach 循环中使用时,Jquery 代码仅对第一个元素起作用

css - 防止元素在更改浏览器选项卡时丢失 CSS "focus"

javascript - Ext.getBody().focus() 在 IE6 中不起作用

javascript - Jquery UI Sortable 在动态容器中不起作用

javascript - twitter-bootstrap 模式确认对话框

php - 如何使用 Ajax 和 jQuery 更改 Blade 表中检索到的数据顺序

JavaScript - 数组值空白

javascript - AJAX 未收到数据 ERR_EMPTY_RESPONSE

android - ScrollView 禁用焦点移动