我是新來編寫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類循環所有元素不同,它循環處理髮生事件的輸入值。我不想將類名添加到插件中,因爲它會添加額外的代碼並使其不夠靈活。
任何意見,將不勝感激。
乾杯
格雷格
這就是我正在尋找的 - 謝謝!我認爲它需要一些重構,但我沒有想到只調用一個函數。我想這就是當你開始某些事情時會發生什麼,然後再去探索它。最初它只是使用'.focus()'和'blur()',但由於我們使用'keyup()',所以不需要使用'.focus()'return語句只是因爲我遵循jQuery插件教程,我真的不知道我在做什麼! :) – shadylane 2011-05-29 06:53:50
@shadylane:沒問題!很高興我能幫上忙。有時它只需要第二雙眼睛。 – 2011-05-29 13:59:21