简体   繁体   English

为什么我的jQuery插件无法删除焦点上的文本并在模糊时重新添加文本?

[英]Why is my jQuery plugin for removing text on focus and re-adding it on blur not working?

I would like the text in the value field of a text box to disappear when that text box gains focus, and then reappear in response to the eventual blur event - but only if the value is empty (that is, if the user hasn't entered anything after putting focus into the text box). 我希望当该文本框获得焦点时,该文本框的value字段中的文本消失,然后响应最终的模糊事件而重新出现-但前提是该值是空的(即,如果用户没有将焦点放在文本框中后输入任何内容)。 So far, I have this: 到目前为止,我有这个:

this.each(function() {  
    obj = $(this);
    var initialText = obj.val();

    obj.focus(function () { 
        if(obj.val() === initialText)
            obj.val("");    
    });


    obj.blur(function () { 
        if(obj.val() ==="")
            obj.val(initialText);   
    });
});  

This plugin works if I have only one element in the page. 如果页面中只有一个元素,则此插件有效。 If I have two elements then it doesn't work. 如果我有两个元素,那就行不通了。 Why would this be? 为什么会这样呢?

The obj variable isn't scoped to the function, it's globally scoped, so there will only be one of them -- set to the last one that the plugin is applied to. obj变量没有作用于函数,而是全局作用域,因此只有其中一个-设置为插件应用的最后一个变量。 Use the var keyword to scope the variable to the anonymous function alone so that there will be one for each thing that the plugin is applied to. 使用var关键字将变量的作用域仅限定于匿名函数,以便对插件应用的每一件事都有一个。

You'll want to write your plugin seperate from your code implementation. 您需要将插件与代码实现分开编写。

Your plugin would look something like this: 您的插件如下所示:

 (function($) {
    $.fn.watermark = function() {  

       return this.each(function() {         
          var obj = $(this);
          var initialText = obj.val();

          obj.focus(function () { 
            if(obj.val() === initialText)
               obj.val(""); 
          });

         obj.blur(function () { 
            if(obj.val() ==="")
                obj.val(initialText);   
         });
       });
    };
 })(jQuery);  

Then to use your plugin: 然后使用您的插件:

$(document).ready(function() {

    $('.watermark').watermark();

});

Additionally as tvanfosson you'll want to include the var keyword on your obj . 另外,作为tvanfosson,您需要在obj上包含var关键字。 If you don't have the var keyword on your obj declaration only the last textbox will have the watermark effect. 如果在obj声明中没有var关键字,则只有最后一个文本框具有水印效果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM