开发者

jQuery Live Functionality

I am trying to setup a script that will feature a "Placeholder" backup for non-html5 browsers. I have everything working on regular site content. What is not working, is when I load content in via ajax.

I need to figure out how to add the .live() function to the script so it will work on ajax loaded conte开发者_JAVA百科nt. Anyone have any advice? I can't seem to figure it out.

jQuery.support.placeholder = false;
test = document.createElement('input');
if('placeholder' in test) jQuery.support.placeholder = true;

if (!jQuery.support.placeholder) { 
    var active = document.activeElement;
    jQuery(':text').focus(function () {
        if (jQuery(this).attr('placeholder') != '' && jQuery(this).val() == jQuery(this).attr('placeholder')) {
            jQuery(this).val('').removeClass('placeholder');
        }
    }).blur(function () {
        if (jQuery(this).attr('placeholder') != '' && (jQuery(this).val() == '' || jQuery(this).val() == jQuery(this).attr('placeholder'))) {
            jQuery(this).val(jQuery(this).attr('placeholder')).addClass('placeholder');
        }
    });

    jQuery(':text').blur();
    jQuery(active).focus();
    jQuery('form').submit(function () {
        jQuery(this).find('.placeholder').each(function() { jQuery(this).val(''); });
    });
}


You just use a slightly different syntax for binding your event handlers. Instead of

jQuery(':text').focus(function () {
    //do stuff here
}.blur {
   // do other stuff here
}

you would do

jQuery(':text').live( "focus", function() {
    //do stuff here
}.live("blur", function() {
    //do other stuff here
}

You should also consider using delegate instead of live, if it's possible to narrow the parts of the page you need to monitor; live can use a lot of resources. For example, if the content you're going to load via ajax will always be within a certain div, use delegate on that div, rather than live (which will monitor the entire document).


in jQuery 1.7:

(function() {
    var test = document.createElement('input');
    if ('placeholder' in test) return;

    var active = document.activeElement;
    $(document).on('focus', ':text', function() {
            if ($(this).attr('placeholder') != '' && $(this).val() == $(this).attr('placeholder')) {
                $(this).val('').removeClass('placeholder');
            }
        }).on('blur', ':text', function() {
            if ($(this).attr('placeholder') != '' && ($(this).val() == '' || $(this).val() == $(this).attr('placeholder'))) {
                $(this).val($(this).attr('placeholder')).addClass('placeholder');
            }
        });

    $(':text').blur();
    $(active).focus();
    $(document).on('submit', 'form', function() {
        $(this).find('.placeholder').each(function() {
            this.value = '';
        });
    });
})();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜