Как бы я превратил это в функцию JQuery? - PullRequest
1 голос
/ 25 августа 2011

У меня есть этот бит JavaScript:

$('.step_1 li').click(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();
  }
});

Я бы хотел сказать $('.step_1').inputSwap(), чтобы я мог использовать его снова.

Так что же нужно для создания такой функции jQuery? (Я использую jQuery 1.6.2)

Ответы [ 3 ]

5 голосов
/ 25 августа 2011

это то, как вы бы превратили его в плагин.

$.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();
            })
    });
}

РЕДАКТИРОВАТЬ

некоторые оптимизации и исправлены 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;
}
2 голосов
/ 25 августа 2011

Учтите это:

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 );
    });
}

Живая демоверсия: http://jsfiddle.net/nbkcP/

Использование delegate обеспечивает лучшую производительность, поскольку вы не привязываете обработчики щелчка / фокуса / размытия непосредственно к соответствующим элементам. Вместо этого jQuery привязывает только один"живой" обработчик к каждому элементу .step_1.

0 голосов
/ 25 августа 2011
$.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();
        }
    });
};

Позвоните с помощью:

$('.step_1').inputSwap()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...