开发者

Possible scope issue with jQuery plugin?

开发者 https://www.devze.com 2023-03-06 19:25 出处:网络
I\'m trying to make a jquery plugin (just for fun) and I can\'t seem to a certain portion to do what I want.

I'm trying to make a jquery plugin (just for fun) and I can't seem to a certain portion to do what I want.

(function($){

    var resetText = function(){ if (this.value == "") this.value = this.title; }
 开发者_StackOverflow   var clearText = function(){ if (this.value == this.title) this.value = ""; }

    $.fn.placeHolder = function() {
        return this.each(function(){
            resetText(); // <-- this doesn't work
            $(this).focus(clearText).blur(resetText);
        });
    };
})(jQuery);

Basically, I want the title attribute to be copied over to the value attribute (if the value is empty) on doc.ready AND on field.blur

As it is now, it works onBlur but not on document.ready

I have a feeling it's a scope thing but honestly I don't know how to fix it.

See for yourself: http://jsfiddle.net/Usk8h/


You have a this issue, not a scope issue.

Do this instead:

resetText.call( this );

The .call() method allows you to set the value of this in the resetText() function to whatever you pass as the first argument.

In this case you're passing the DOM element represented by this in the .each().


EDIT:

You could actually reduce your the plugin down to this:

$.fn.placeHolder = function() {
    return this.focus(clearText).blur(resetText).blur(); // <-- triggers blur
};


It does appear to be a scope issue. How about this?

http://jsfiddle.net/Usk8h/1/

(function($){

    var resetText = function(myThis){ if (myThis.value == "") myThis.value = myThis.title; }
    var clearText = function(myThis){ if (myThis.value == myThis.title) myThis.value = ""; }

    $.fn.placeHolder = function() {
        return this.each(function(){
            resetText(this);
            $(this)
                .focus(function(){
                    clearText(this);
                }).blur(function(){
                    resetText(this);   
                });
        });
    };
})(jQuery);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号