2012-02-19 126 views
0

我似乎无法得到这个工作:下面的代码:jQuery回调函数?

// Clears the default text on click, but restores if nothing is entered 
var clearText = (function(){ 
    $("input:text").each(function() { 

     var default_value = this.value; 

     $(this).focus(function(){ 
       if(this.value == default_value) { 
         this.value = ''; 
       } 
     }); 

     $(this).blur(function(){ 
       if(this.value == '') { 
         this.value = default_value; 
       } 
     }); 

    }); 

    $("textarea").each(function() { 

     var default_value = this.value; 

     $(this).focus(function(){ 
       if(this.value == default_value) { 
         this.value = ''; 
       } 
     }); 

     $(this).blur(function(){ 
       if(this.value == '') { 
         this.value = default_value; 
       } 
     }); 

    }); 

})(); 


$('html').on('keydown', 'body', function(e){ 
    if (e.which == 9) 
    { 
     clearText(); 
    } 
}); 

明文()肯定是被称为在页面加载,但随后并没有作为一个回调函数工作呢?我不完全确定为什么,有谁能帮我解决问题?

干杯

回答

2

clearText是未定义的,它不是函数。你正在调用它,因为你认为你正在定义它。这就是函数赋值最后的()。

var clearText = function(){ 
    $("input:text").each(function() { 

     var default_value = this.value; 

     $(this).focus(function(){ 
       if(this.value == default_value) { 
         this.value = ''; 
       } 
     }); 

     $(this).blur(function(){ 
       if(this.value == '') { 
         this.value = default_value; 
       } 
     }); 

    }); 

    $("textarea").each(function() { 

     var default_value = this.value; 

     $(this).focus(function(){ 
       if(this.value == default_value) { 
         this.value = ''; 
       } 
     }); 

     $(this).blur(function(){ 
       if(this.value == '') { 
         this.value = default_value; 
       } 
     }); 

    }); 

}; 

现在的功能是可调用

+0

有没有一种方法可以让它在自定义时自动调用,并且使clearText成为一个函数? – chintanparikh 2012-02-19 07:42:39

+0

是的,有几种方法可以做到这一点。但是不要保存一行代码是不值得的,它有点神秘。定义函数并调用它们。那就是人的思维是如何运作的。只需添加clearText();在你定义它之后,每个人都会知道发生了什么。 – 2012-02-19 07:48:18

+0

哎呀,感谢您的帮助 – chintanparikh 2012-02-19 07:50:27

0

试图把你函数中的document.ready即

$(document).ready(function(){ 
    // Your functions here... 
    $("input:text").each(function(e){ 
    // code goes here... 
    }); 
}); 

没有必要把它包内的另一个大括号/()。

+0

对不起,我应该说,我上面发布的是代码片段,所有内容实际上都在$(document).ready – chintanparikh 2012-02-19 07:46:37

+0

我已经更新了答案。 – 2012-02-19 07:51:03