jQuery onblur 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2355604/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:19:13  来源:igfitidea点击:

jQuery onblur not working

jqueryonblur

提问by Isis

$('#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"/>


onblurnot working.
Any ideas?


onblur不起作用。
有任何想法吗?

回答by Amr Elgarhy

Use liveinstead of focus and blur

使用实时而不是聚焦和模糊

.live() has been deprecated. Use .on()and .off()instead.

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

because you are adding the input in run time, so it adds to the page with out the events, live:

因为您是在运行时添加输入,所以它添加到没有事件的页面,实时:

Attach a handler to the event for all elements which match the current selector, now or in the future.

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

Example:

例子:

$('#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);
});

回答by Nick Craver

This for your exact code:

这是您的确切代码:

$('#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);
});

回答by Mark Schultheiss

The first issue I see is that your selector is an ID of #lPass, yet, within that selector you attempt to insert a new tag with that same ID. ID must be unique on the page. THEN you attempt to remove with the .remove() - seems to make no sense to me.

我看到的第一个问题是您的选择器是 #lPass 的 ID,但是,在该选择器中,您尝试插入具有相同 ID 的新标签。ID 在页面上必须是唯一的。然后你试图用 .remove() 删除 - 对我来说似乎没有意义。

Just use the .remove() or use a new id...

只需使用 .remove() 或使用新的 id ...

OR clarify what you want to do.

或澄清你想做什么。

As for the .blur, just use a blur, but the ID must be fixed, or use the .live() as others suggest if you wish to blur the NEW field you added.

至于 .blur,只需使用模糊,但 ID 必须固定,或者如果您希望模糊添加的新字段,则使用 .live() 就像其他人建议的那样。