Jquery .代表问题

Jquery .代表问题,jquery,Jquery,我使用以下代码在文本字段中显示一个文本,当您关注它时,该文本字段会显示: $(document).ready(function(){ $('.onfocus_rem_txt').each(function(){ $(this).val($(this).attr('defaultVal')); $(this).css({color:'grey'}); }); $('.onfocus_rem_txt').focus(function(){ if ($(this).va

我使用以下代码在文本字段中显示一个文本,当您关注它时,该文本字段会显示:

$(document).ready(function(){
  $('.onfocus_rem_txt').each(function(){
   $(this).val($(this).attr('defaultVal'));
   $(this).css({color:'grey'});
  });

  $('.onfocus_rem_txt').focus(function(){
   if ($(this).val() == $(this).attr('defaultVal')){
   $(this).val('');
   $(this).css({color:'black'});
   }
  });

  $('.onfocus_rem_txt').blur(function(){
   if ($(this).val() == ''){
   $(this).val($(this).attr('defaultVal'));
   $(this).css({color:'grey'});
   }
  });
});

我如何使用.delegate才能在我打开的每个新的.php页面中使用它???

您可以委托
.focus
.blur
这样的事件,不需要使用
进行迭代。每个
,只要在创建
输入
元素时预先应用值和文本颜色即可

例如:


您可以使用live在多个位置使用此功能

$(document).ready(function(){
  $('.onfocus_rem_txt').each(function(){
     $(this).val($(this).attr('defaultVal'));
     $(this).css({color:'grey'});
  }).live({
     'focus': function(){
       if ($(this).val() == $(this).attr('defaultVal')){
         $(this).val('');
         $(this).css({color:'black'});
       },
     'blur': function(){
       if ($(this).val() == ''){
        $(this).val($(this).attr('defaultVal'));
        $(this).css({color:'grey'});
       }

  });
});

你可以把它连接到页面的主体,但这就是为什么他们有live()
$(document).ready(function(){
  $('.onfocus_rem_txt').each(function(){
     $(this).val($(this).attr('defaultVal'));
     $(this).css({color:'grey'});
  }).live({
     'focus': function(){
       if ($(this).val() == $(this).attr('defaultVal')){
         $(this).val('');
         $(this).css({color:'black'});
       },
     'blur': function(){
       if ($(this).val() == ''){
        $(this).val($(this).attr('defaultVal'));
        $(this).css({color:'grey'});
       }

  });
});