jQuery Live功能

时间:2011-03-03 20:11:25

标签: jquery html5 live

我正在尝试设置一个脚本,该脚本将为非html5浏览器提供“占位符”备份。我有一切都在处理常规网站内容。什么不起作用,是我通过ajax加载内容。

我需要弄清楚如何将.live()函数添加到脚本中,以便它可以处理ajax加载的内容。有人有什么建议吗?我似乎无法弄明白。

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

2 个答案:

答案 0 :(得分:3)

您只需使用稍微不同的语法来绑定事件处理程序。而不是

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

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

如果可以缩小您需要监控的页面部分,您还应该考虑使用delegate而不是live; live可以使用大量资源。例如,如果您要通过ajax加载的内容将始终位于某个div中,请在该div上使用delegate,而不是live(将监视整个文档)。

答案 1 :(得分:0)

在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 = '';
        });
    });
})();
相关问题