2011-05-29 64 views
1

我是新來編寫jQuery插件,所以我有點不確定如何做到這一點。該插件將標籤顯示爲文本和密碼輸入內的提示。這很簡單 - 在元素焦點上,標籤是隱藏的。同樣在文檔加載時,它會檢查瀏覽器是否已自動完成任何字段格式 - 如果是,則隱藏該標籤。我遇到的問題是其他字段的自動填充。爲了解決這個問題,我試圖將一個函數綁定到元素的onblur和keyup事件,以循環其他表單元素並確定它們是否已經自動完成。jQuery插件循環通過兄弟姐妹

這是註釋的代碼。

(function($){ 
    $.fn.innerLabels = function() { 
    return this.each(function() {   
    var $this = $(this); 
// Initialise all form elements with class 
    $this.each(function() { 
    var lngth = $(this).val().length; 
    if(lngth > 0){ 
     $(this).parent().children('label').hide(); 
    }else{ 
     $(this).parent().children('label').show(); 
    }; 
    }); 
// onfocus event - clears label 
    $this.focus(function() { 
    $this.parent().children('label').hide(); 
    }); 
// onblur/keyup event re-enstates label if length of value is zero or hides if autocompleted. 
    $this.bind("blur keyup",function() { 
// check all fields in case of autocomplete <- this is the problem 
    $(this).each(function() { 
    var lngth = $(this).val().length; 
    //alert(lngth); 
    if(lngth > 0){ 
     $(this).parent().children('label').hide(); 
    }else{ 
     $(this).parent().children('label').show(); 
    }; 
    }); 
    }); 
    }); 
    }; 
})(jQuery); 

這是通過這樣做觸發的。

$(document).ready(function(){ 
    $('.txtbox').innerLabels(); 
}); 

.txtbox是我添加的一個類,用於形成我想要使用它的文本和密碼字段。

我認爲這是一個範圍問題。最後一個$(this).each是問題所在。與使用.txtbox類循環所有元素不同,它循環處理髮生事件的輸入值。我不想將類名添加到插件中,因爲它會添加額外的代碼並使其不夠靈活。

任何意見,將不勝感激。

乾杯

格雷格

回答

0

只要看你的代碼,它看起來像你試圖在模糊再次執行初始化代碼。是這樣嗎?如果是這樣,那重構普通代碼的功能和簡單地從你的事件處理程序調用它:

(function($) { 
    $.fn.innerLabels = function() { 
     var $self = this; 
     var hideElements = function() { 
      $self.each(function() { 
       var lngth = $(this).val().length; 
       if (lngth > 0) { 
        $(this).parent().children('label').hide(); 
       } else { 
        $(this).parent().children('label').show(); 
       }; 
      }); 
     }; 

     hideElements(); 

     return $self.focus(function() { 
      $(this).parent().children("label").hide(); 
     }).bind("blur keyup", hideElements); 
    }; 
})(jQuery); 

一些重構之後,我還沒有看到爲.each調用(在return語句)的需要,因爲分配事件處理程序將適用於匹配元素集合中的每個項目。

希望這就是你以後的樣子。

+0

這就是我正在尋找的 - 謝謝!我認爲它需要一些重構,但我沒有想到只調用一個函數。我想這就是當你開始某些事情時會發生什麼,然後再去探索它。最初它只是使用'.focus()'和'blur()',但由於我們使用'keyup()',所以不需要使用'.focus()'return語句只是因爲我遵循jQuery插件教程,我真的不知道我在做什麼! :) – shadylane 2011-05-29 06:53:50

+0

@shadylane:沒問題!很高興我能幫上忙。有時它只需要第二雙眼睛。 – 2011-05-29 13:59:21

0

在jQuery中您可以使用next()函數

$(this).next() 

將選擇下一個選擇的兄弟姐妹。

More on next()

+1

我想你的意思是'$(this).next()':http://api.jquery.com/next/ – lambacck 2011-05-29 02:45:14

+0

你是對的@lambacck謝謝你的更正 – Ibu 2011-05-29 02:47:58

+0

謝謝,但那不是很完美我在找什麼。文本輸入嵌套在其他標記中。在'keyup()'或'blur()'事件中,我希望函數檢查所有表單元素以查看是否有任何自動完成。檢查下面的安德魯·惠特克的回答。 – shadylane 2011-05-29 07:01:23