jQuery focusin和focusout实时事件未触发 [英] jQuery focusin and focusout live events are not firing

查看:131
本文介绍了jQuery focusin和focusout实时事件未触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

jQuery版本:1.4.1

我正在尝试编写一个简单的水印类型插件,并且我想利用实时事件,因为并非所有需要使用它的元素都将在页面加载期间存在,或者可以从页面中添加和删除它们. DOM.但是,由于某些原因,这些事件永远不会触发.

I am attempting to write a simple watermark type plugin and I want to take advantage of live events since not all of the elements I need to use it on will exist during the page load, or they may be added and removed from the DOM. However, for some reason the events never fire.

这是无效代码:

; (function($) {

    $.fn.watermark = function(text) {

        return $(this).each(function() {
            $(this).live('focusout', function() {
                if (this.value == "") {
                    this.value = text;
                }

                return false;
            });

            $(this).live('focusin', function() {
                if (this.value == text) {
                    this.value = "";
                }

                return false;
            });
        });
    }

})(jQuery);

我可以在不使用现场活动的情况下使它正常工作.这段代码可以正常工作:

I can get this to work without using live events. This code does work:

; (function($) {

    $.fn.watermark = function(text) {

        return $(this).each(function() {
            $(this).focusout(function() {
                if (this.value == "") {
                    this.value = text;
                }

                return false;
            });

            $(this).focusin(function() {
                if (this.value == text) {
                    this.value = "";
                }

                return false;
            });
        });
    }

})(jQuery);

推荐答案

.live()需要一个选择器而不是DOM元素,在您调用它的地方,它仅在DOM元素上,所以要代替这个:

.live() needs a selector not a DOM element, in the place you're calling it, it's only on a DOM element, so instead of this:

$(this).each(function() {
        $(this).live('focusout', function() {

尝试一下(this已经是一个jQuery对象):

Try this (this is already a jQuery object):

this.live('focusout', function() {

之所以需要它,是因为 .live() 的工作原理气泡到document时,它会检查选择器...如果没有选择器,则无法对其进行检查.另外,如果您具有DOM元素,并且事件处理程序仅用于 ,则 .live() 并没有多大意义:)

It needs this because of how .live() works, when an event bubbles up to document it checks that selector...if there's no selector, there's no way for it to check. Also, if you have a DOM element and the event handler is for only it, .live() wouldn't make much sense anyway :)

这篇关于jQuery focusin和focusout实时事件未触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆