jQuery focusin和focusout直播活动没有解雇

jQuery版本:1.4.1

我正在尝试编写一个简单的水印类型插件,我想利用实时事件,因为我不需要在页面加载期间存在我需要使用它的所有元素,或者可以在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() { 

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

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

它需要这个,因为.live()工作方式,当一个事件冒泡到document时检查选择器……如果没有选择器,就没有办法检查它。 此外,如果你有一个DOM元素,并且事件处理程序仅用于它,那么.live()无论如何都没有多大意义:)

看看这里。

在jQuery .live()方法中模拟“焦点”和“模糊”

尝试:

 $(document).ready(function(){ $('input[type=search]').bind('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_block { position: relative; } input[type=search] { width: 100px; padding: 10px 10px 10px 30px; } /* -- SVG - https://www.iconfinder.com/iconsets/ionicons ----- */ svg { position: absolute!important; left: 10px; transform: translateY(55%); top: 0; } svg.cancel { display: none; }