jquery优先执行

谁能帮我这个:

$('#n').click(function() { $(this).parent().append(' delete'); $(this).next().click(function() { alert('clicked'); //this not working }); $(this).blur(function() { $(this).next().remove(); }); }); 

JS小提琴演示 ; 问题是在click()事件之前执行blur() click()事件。

您可以使用超时将推迟推迟几毫秒。

示例: http : //jsfiddle.net/vkun9/7/

 $(this).blur(function() { var _this = this; setTimeout(function(){$(_this).next().remove();},100); }); 

我还将附加的blur移动到了单击处理程序之外,因为每次单击元素时它都会添加一个,并将单击处理程序更改为焦点以避免多次remove按钮重复单击输入,如@ dheerosaur指出。

所以

 $('#n') .focus(function() { $(this).parent().append(' delete'); $(this).next().click(function() { alert('clicked'); //this not working }); }) .blur(function() { var _this = this; setTimeout(function(){$(_this).next().remove();},100); }); 

但是,您所经历的并不是问题。 这是正常的行为,因为元素需要在另一个元素拥有它之前失去焦点( 触发模糊 )。

您还应该将属性标签与input元素的id匹配。

使用外部事件插件 ,你可以这样做:

 $('.input_field input').focus(function() { var div = $(this).parent(); var link = $('delete').click(function(e) { e.preventDefault(); alert('clicked'); }).appendTo(div); $(this).data('delete', link); }).bind('focusoutside clickoutside', function(e) { var link = $(this).data('delete'); if (link && e.target != link[0]) { link.remove(); } }); 

首先切换到使用焦点事件而不是输入字段上的click事件,有些人实际上使用键盘来浏览表单字段;-)。

然后创建删除链接,将其添加到页面并在输入字段中存储对它的引用。

然后使用外部事件插件,我们可以绑定focusoutside和clickoutside,当用户在输入字段外单击或单击时,会触发这些插件。 通过检查事件的目标是删除链接,我们可以告诉我们是否应该删除链接。

示例: http : //jsfiddle.net/petersendidit/vkun9/6/

您可以尝试在模糊事件中设置非常短的超时。 这对我有用。

  $(this).blur(function() { setTimeout(function(){$(this).next().remove();}, 1); }); 

而不是使用blur()我把一个基于hover()的方法放在一起,虽然它确实有一个稍微笨重的if / else语句:

 $('.input_field').hover( function(){ if ($(this).find('.delete').length) { return false; } else { $('delete') .appendTo($(this)); } }, function(){ if ($('#n').is(':focus')){ return false; } else { $(this).find('.delete').remove(); } } ); 

JS小提琴演示 。

但是,这种方法确保只有一个删除链接附加到input_field (而不是在原始演示中多次单击input附加的多个链接)。