jquery优先执行

Nic*_*ick 5 javascript jquery

谁能帮我这个:

$('#n').click(function() {
    $(this).parent().append('<a href="javascript:void()">&nbsp;delete</a>');
    $(this).next().click(function() {
        alert('clicked'); //this not working
    });
    $(this).blur(function() {
        $(this).next().remove();
    });
});
Run Code Online (Sandbox Code Playgroud)

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

Gab*_*oli 6

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

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

$(this).blur(function() {
            var _this = this;
            setTimeout(function(){$(_this).next().remove();},100);
        });
Run Code Online (Sandbox Code Playgroud)

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

所以

$('#n')
    .focus(function() {
        $(this).parent().append('<a href="javascript:void()">&nbsp;delete</a>');
        $(this).next().click(function() {
            alert('clicked'); //this not working
        });
    })
    .blur(function() {
        var _this = this;
        setTimeout(function(){$(_this).next().remove();},100);
    });
Run Code Online (Sandbox Code Playgroud)

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

您还应该将label for属性与input元素的id 匹配.