How would I turn this into a jQuery function?
I have this bit of javascript:
$('.step_1 li').cli开发者_JAVA百科ck(function(event) {
$(this).find('label').hide();
$(this).find('input').focus();
});
$('.step_1 li input')
.focus(function(){
$(this).prev('label').hide();
})
.blur(function(){
if (!$(this).val()){
$(this).prev('label').show();
}
});
I'd like to be able to just say $('.step_1').inputSwap()
so I can reuse it.
So what's the proper wan to create a jQuery function like this? (I'm running jQuery 1.6.2)
this is how you would turn it into a plugin.
$.fn.inputSwap = function(){
return this.each(function(){
$(this)
.click(function(){
$(this).find("label").hide();
$(this).find('input').focus();
}).find("input").focus(function(){
$(this).prev('label').hide();
}).blur(function(){
$(this).prev('label').show();
})
});
}
EDIT
some optimizations and fixed li
$.fn.inputSwap = function(){
this.find('li').click(function(){
var $li = $(this);
$li.find("label").hide();
$li.find('input').focus();
}).find("input").focus(function(){
$(this).prev('label').hide();
}).blur(function(){
$(this).prev('label').show();
});
return this;
}
Consider this:
function inputSwap( clss ) {
var j = $( clss );
j.delegate( 'li', 'click', function () {
$( this ).find( 'label' ).hide();
$( this ).find( 'input' ).focus();
});
j.delegate( 'input', 'focus', function () {
$( this ).prev( 'label' ).hide();
});
j.delegate( 'input', 'blur', function () {
$( this ).prev( 'label' ).toggle( !this.value );
});
}
Live demo: http://jsfiddle.net/nbkcP/
Using delegate
ensures better performance, because you're not binding any click / focus / blur handlers to the corresponding elements directly. Instead, jQuery binds only one "live" handler to each .step_1
element.
$.fn.inputSwap = function(){
return this.find('li').click(function(event) {
$(this).find('label').hide().end().find('input').focus();
}).find('input').focus(function(){
$(this).prev('label').hide();
}).blur(function(){
if (!$(this).val()){
$(this).prev('label').show();
}
});
};
Call it with:
$('.step_1').inputSwap()
精彩评论