focus() 與 blur() 是表單互動的兩大基石:前者在元素取得焦點時觸發,後者在失去焦點時觸發。輸入框的提示文字、即時驗證、自動完成提示,大多靠這兩個事件搭配。
$(function(){
$("#input").focus(function(){
// 這裡寫獲得焦點之後運行的代碼
}).blur(function(){
// 這裡寫失去焦點之後運行的代碼
});
})
把 #input 換成你的 input 的 ID 即可。
一個常見的編輯模式:頁面上先顯示文字,雙擊後原地變成輸入框,讓使用者直接修改。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>無標題文檔</title>
<script src="/js/jquery-1.4.4.js"></script>
<script>
$(document).ready(function()
{
$("#nameBefore").dblclick(function()
{
$("#nameBefore").replaceWith("<div id='nameIn'><input type='text' name='nameInVal' id='nameInVal' value='In' /></div>");
});
// 失去焦點以後
$("#nameInVal").live("blur", function()
{
alert('nameInVal已失去焦點');
});
}
);
</script>
</head>
<body>
<form name="testfm" method="post" action="save.php">
<table>
<tr><td>1</td><td><div id='nameBefore'>Before</div></td></tr>
</table>
</form>
</body>
</html>
注意 #nameInVal 的 blur 綁定用的是 live() 而不是 .blur()。原因很單純:這個元素在頁面載入時根本不存在,它是雙擊之後才被動態產生的。若用 $("#nameInVal").blur(...),該行執行時選到的是空集合,綁定等於沒做。
live() 從 jQuery 1.4 起支援 focus/blur(在更早的版本中,這兩個事件因不冒泡而無法被委派)。在 IE 與 Firefox 中都測試無誤。
live() 已在 jQuery 1.9 中移除,請改用 on() 的事件委派:
$(document).on("blur", "#nameInVal", function(){
// 失去焦點的處理
});
另外提醒一個實務陷阱:focus/blur 不冒泡,因此不能像 click 那樣直接委派。若需要冒泡版本,請使用 focusin/focusout:
$(document).on("focusout", ".field", function(){
// 會冒泡,可委派
});
這點差異是很多人從 live() 遷移到 on() 時踩到的坑,值得記住。