【问题标题】:Possible scope issue with jQuery plugin?jQuery插件可能的范围问题?
【发布时间】:2011-08-27 12:29:11
【问题描述】:

我正在尝试制作一个 jquery 插件(只是为了好玩),但我似乎无法在某个部分做我想做的事。

(function($){

    var resetText = function(){ if (this.value == "") this.value = this.title; }
    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);

基本上,我希望将 title 属性复制到 doc.ready 和 field.blur 上的 value 属性(如果值为空)

就像现在一样,它适用于Blur,但不适用于 document.ready

我觉得这是一个范围问题,但老实说我不知道​​如何解决它。

自己看看:http://jsfiddle.net/Usk8h/

【问题讨论】:

    标签: jquery plugins jquery-plugins scope


    【解决方案1】:

    这似乎是一个范围问题。这个怎么样?

    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);
    

    【讨论】:

    • 感谢您的努力!最终,我喜欢提供更好的其他解决方案。我只是看起来更干净,更易于维护。不过,您的解决方案确实有效,因此感谢您抽出宝贵时间。
    【解决方案2】:

    您有一个this 问题,而不是范围问题。

    改为这样做:

    resetText.call( this );
    

    .call() 方法允许您将resetText() 函数中this 的值设置为作为第一个参数传递的任何值。

    在这种情况下,您将在.each() 中传递由this 表示的DOM 元素。


    编辑:

    您实际上可以将您的插件缩减为:

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

    【讨论】:

    • @Johnny 我觉得这很有趣,所以我读了一点,有趣的解释在这里:devlicio.us/blogs/sergio_pereira/archive/2009/02/09/…
    • @kingjiv - 我做了同样的事情并找到了类似的文章。感谢那!我最终选择了触发 onBlur 事件的第二个选择,但我仍然很高兴知道您可以覆盖 this。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-23
    • 1970-01-01
    • 1970-01-01
    • 2011-11-02
    • 1970-01-01
    • 1970-01-01
    • 2012-04-05
    相关资源
    最近更新 更多