2011-05-17 70 views
2

我想做一個jQuery插件(只是爲了好玩),我似乎無法做到我想要的某個部分。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

像現在,它的工作原理的onblur但不是在document.ready

我有一種感覺這是一個範圍的事情,但老實說,我不知道如何解決它。

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

回答

3

你有一個this問題,而不是一個範圍問題。

而是執行此操作:

resetText.call(this); 

.call()方法允許你設置的this的價值,無論你傳遞作爲第一個參數的resetText()功能。

在這種情況下,您在.each()中傳遞this代表的DOM元素。


編輯:

其實你可以轉降低你的插件到這一點:

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

@Johnny我發現這很有趣,所以我在這裏讀了一下,有趣的解釋:http://devlicio.us/blogs/sergio_pereira/archive/2009/02/09/javascript-5-ways-to-call- a-function.aspx – 2011-05-17 20:55:35

+0

@kingjiv - 我做了同樣的事情,發現了一篇類似的文章。感謝那!我最終選擇了觸發onBlur事件的第二選擇,但我仍然很高興知道您可以覆蓋_this_。 :) – Johnny 2011-05-18 14:19:29

0

它似乎是一個範圍的問題。這個怎麼樣?

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

感謝你的努力!最終,我更喜歡另一種解決方案。我看起來更清潔,更易於維護。儘管您的解決方案仍然有效,但非常感謝您的時間。 – Johnny 2011-05-18 14:21:26