jQuery focusin和focusout live事件未触发

jQuery focusin和focusout live事件未触发,jquery,Jquery,jQuery版本:1.4.1 我正在尝试编写一个简单的水印类型插件,我想利用live events,因为在页面加载期间,并非所有需要使用它的元素都存在,或者它们可能会从DOM中添加或删除。然而,由于某些原因,这些事件从未发生过 以下是无效代码: ; (function($) { $.fn.watermark = function(text) { return $(this).each(function() { $(this).live('foc

jQuery版本:1.4.1

我正在尝试编写一个简单的水印类型插件,我想利用live events,因为在页面加载期间,并非所有需要使用它的元素都存在,或者它们可能会从DOM中添加或删除。然而,由于某些原因,这些事件从未发生过

以下是无效代码:

; (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);
我可以在不使用实时事件的情况下实现这一点。此代码确实有效:

; (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元素上,因此,请不要这样做:

$(this).each(function() {
        $(this).live('focusout', function() {
尝试以下操作(
已经是jQuery对象):

它需要这样做是因为它是如何工作的,当一个事件冒泡到
文档
时,它会检查该选择器……如果没有选择器,它就无法检查。另外,如果您有一个DOM元素,并且事件处理程序仅用于它,那么无论如何也没有多大意义:)

请看这里

试试:

$(文档).ready(函数(){
$('input[type=search]')。绑定('focusin',function(){
$(this.animate({width:'300px'},500);
$('svg.magnifier').hide();
$('svg.cancel').show();
}).bind('focusout',function(){
$('svg.cancel').hide();
$('svg.magnifier').show();
$(this.animate({width:'100px'},500);
});
});
div.box\u块{
位置:相对位置;
}
输入[类型=搜索]{
宽度:100px;
填充:10px 10px 10px 30px;
}
/* --
SVG-https://www.iconfinder.com/iconsets/ionicons
----- */
svg{
位置:绝对!重要;
左:10px;
转化:translateY(55%);
排名:0;
}
svg.cancel{
显示:无;
}


$(this)。每个
都应该被这个替换。每个
都是出于同样的原因。@jAndy-实际上他根本不需要这个
。each()
,只需要链式选择器:)这里似乎有些不对劲。我想你应该一直用这个。每个?请参阅:这应该不是必需的,因为我使用的是1.4.1版。这个问题是一个解决办法,因为以前版本的jquery不支持将focusin和focusout用作实时事件。
this.live('focusout', function() {