2010-03-01 57 views
10
$('#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不工作。
任何想法?的jQuery的onblur不工作

回答

24

使用live,而不是重點和模糊

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

,因爲你要添加在運行時輸入的,所以把它添加到頁面出來的事件,住:

連接處理程序的事件匹配當前 所有 元素選擇器,現在或將來。

例子:

$('#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來做。在引號這第一部分功能之前,告訴它你要找什麼樣的事件爲(重點在一審中,模糊在第二)。然後你定義你想要發生的事情。 – 2010-03-01 12:27:00

+6

.live被移除的jQuery 1.9+的,使用。對代替 – 2013-02-21 14:40:04

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

第一個問題,我看到的是,你的選擇是#lPass的ID,但是,內選擇器嘗試插入具有相同ID的新標籤。 ID在頁面上必須是唯一的。那麼你試圖用.remove()去除 - 似乎對我沒有意義。

只需使用一個.remove(),或使用新的ID ...

或澄清你想要做什麼。

對於.blur,只是用一個模糊,但ID必須是固定的,或者使用.live()作爲他人建議,如果你想模糊添加的新領域。