2013-10-10 25 views
2

我想在焦點時更改html中文本框的顏色。但是我的顏色沒有變化。爲什麼我的焦點()在jquery不工作?

的Html

<!DOCTYPE html> 
<html> 
<head> 
    <title>Make a new account</title> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 
    <script src="script.js" type="text/javascript" ></script> 
</head> 
<body> 
    <h2 align="center" class="Heading">Want an account</h2> 
    <h3 align="center" class="Heading">Enter your details</h3> 
    <div align="center"> 
    <form name="Info_Form"> 
    <table> 
    <tr> 
     <td class="TD">Your Name Pal :</td> <td><input type="text" name="Name"></td> 
    </tr> 
    <tr> 
     <td class="TD">Your Password :</td> <td><input type="password" name="pwd"></td> 
    </tr> 
    <tr> 
     <td align="right" ><input type="submit" value="Submit"></td> 
    </tr> 
    </table> 
    </form> 
    </div> 
</body> 
</html> 

我的js文件:

$(document).ready(function(){ 
$('h2').fadeOut(3000); 
$(".TD").focus(function(){ 
    $(this).css("background-color","blue"); 
    }); 
}); 

我到底做錯了什麼?

+0

如何ü可以專注2個元件在同一時間在窗體上?? – iJade

+0

@iJay他試圖捕捉的焦點事件,不分配焦點;) – Archer

+0

@Archer啊....我的壞....是一種倉促 – iJade

回答

2

代替:

$(".TD").focus(function(){ 
    $(this).css("background-color","blue"); 
    }); 

使用:

$("input").focus(function(){ 
    $(this).css("background-color","blue"); 
    }); 
+0

準確的!我也發佈類似的,但得到了一個downvote。 – Jai

2

這是因爲你可以申請.focus()只的元素(鏈接,表單輸入)的數量有限。

jQuery documentation來自:當它獲得焦點

焦點事件被髮送給一個元素。此事件 隱式適用於有限的一組元素,例如表單 元素(,等)和鏈接()。在近期的 瀏覽器版本中,可以通過顯式設置元素的tabindex屬性將事件擴展爲包含所有元素 類型。一個 元素可以通過鍵盤命令獲得焦點,例如Tab鍵,或者通過鼠標點擊元素獲得焦點。

在這裏,您嘗試將其應用於<td>標記。

此外,您的<input>不是.TD的孩子,所以這是您的代碼中的另一個問題。

爲什麼不能簡單地用CSS :focus選擇來實現這一目標?