简体   繁体   English

jQuery:焦点/模糊事件在输入替换后不起作用

[英]jquery: focus/blur events don't work after input replacement

I have a simple input element with the following attributes: 我有一个具有以下属性的简单输入元素:

<input id="InputPassword" type="password" value="Password" class="initClass"/>

In order set a cross-browser placeholder for it I use testFocusBlur function 为了为其设置跨浏览器占位符,我使用了testFocusBlur函数

function testFocusBlur(){
$('input').focus(function () {
    if($(this).attr('type')=='text'){
       var campoPassword=$(this);
       replaceInputType(campoPassword[0], 'password')
    }
}).blur(function () {
    if($(this).attr('type')=='password'){
    var campoPassword=$(this);
    replaceInputType(campoPassword[0], 'text')
    }
});
$('input').blur();

} }

which, on $(document).ready event: 在$(document).ready事件中:

  1. calls the blur event on the input element; 在输入元素上调用blur事件;
  2. if type=password call the replaceInputType javascript function; 如果type = password,请调用replaceInputType javascript函数;
  3. replaceInputType function creates a new dom input element, set type=text for it, get the attributes of the old input elements and change the class from initClass to newClass; replaceInputType函数创建一个新的dom输入元素,为其设置type = text,获取旧输入元素的属性并将该类从initClass更改为newClass;
  4. append the new input element to the same div 将新输入元素附加到同一div

the above works correctly but, once the new input element is set, and I focus on it, the initial testFocusBlur function doesn't work anymore 上面的方法可以正常工作,但是,一旦设置了新的输入元素,并且我专注于此,初始的testFocusBlur函数就不再起作用

see: http://jsfiddle.net/4tRzs/2/ 参见: http : //jsfiddle.net/4tRzs/2/

note: i don't want to set an inline function in the input such as onfocus="...." 注意:我不想在输入中设置内联函数,例如onfocus =“ ....”

Please help, Thanks. 请帮忙,谢谢。

You need to use on function from jQuery 您需要使用jQuery中的on函数

$(document).on("focus" , "input", function(){
   ...
}

on is the old live function. on是旧的live功能。 documentation 文件资料

You will have something like this in your function: 您的函数中将具有以下内容:

function testFocusBlur(){
$(document).on("focus", 'input', function () {
    if($(this).attr('type')=='text'){
       var campoPassword=$(this);
       replaceInputType(campoPassword[0], 'password')
    }
})
$(document).on("blur", "input", function () {
    if($(this).attr('type')=='password'){
    var campoPassword=$(this);
    replaceInputType(campoPassword[0], 'text')
    }
});
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM