我是新来编写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