jQuery失去焦点事件(onblur)无法正常工作

12
$('#lPass').focus(function() {  
        if (this.value == this.defaultValue) this.value = '';
        $(this).after('<input type="password" id="lPass" size="10" value="'+this.value+'"/>').remove();
}).blur(function() {
    alert(1);
});

<input id="lPass" type="text" size="10" value="Password"/>


onblur不起作用。
有什么想法吗?

3个回答

34

使用 live 代替 focus 和 blur

.live() 已经被弃用。请使用 .on().off() 代替。

因为您在运行时添加了输入框,所以它们被添加到页面上时没有事件,可以使用 live:

为所有匹配当前选择器的元素附加一个事件处理程序,现在或将来。

示例:

$('#lPass').on('focus', function() {
    if (this.value == this.defaultValue) this.value = '';
    $(this).after('<input type="password" id="lPass" size="10" value="' + this.value + '"/>').remove();
});


$('#lPass').on('blur', function() {
    alert(1);
});

1
".live告诉jQuery,你希望这个事件发生在某些东西上,无论它是在原始文件中还是由JavaScript创建的。引号中的第一部分告诉它你正在寻找什么样的事件(在第一个例子中是焦点,第二个例子中是模糊)。然后,你定义你想要发生的事情。" - user241244
10
自jQuery 1.9+版本起,.live方法已被移除,请改用.on方法。 - Mark Schultheiss

2
这是您的准确代码:
$('#lPass').live('focus', function() {  
    if (this.value == this.defaultValue) this.value = '';
    $(this).after('<input type="password" id="lPass" size="10" value="'+this.value+'"/>').remove();
}).live('blur', function() {
    alert(1);
});

2
我看到的第一个问题是你的选择器是一个ID为#lPass,然而在该选择器中,你试图插入一个具有相同ID的新标签。ID必须在页面上唯一。然后你尝试使用.remove()来删除,对我来说似乎没有意义。
只需使用.remove()或使用一个新的ID...
或者澄清你想要做什么。
至于.blur,只需使用模糊效果,但ID必须固定,或者像其他人建议的那样使用.live()如果你希望模糊新添加的字段。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接