簡體   English   中英

為什么我在jquery中的focus()無法正常工作?

[英]Why my focus() in jquery not working?

焦點時,我想更改html中文本框的顏色。 但是我的顏色沒有改變。

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");
  });
});

我究竟做錯了什么?

這是因為您只能將.focus()應用於有限數量的元素(鏈接,表單輸入)。

jQuery文檔中

焦點事件在獲得焦點時發送到元素。 此事件隱式適用於有限的一組元素,例如表單元素(,等)和鏈接()。 在最新的瀏覽器版本中,可以通過顯式設置元素的tabindex屬性將事件擴展為包括所有元素類型。 元素可以通過鍵盤命令(例如Tab鍵)或通過單擊元素來獲得焦點。

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

而且,您的<input>不是.TD的子.TD ,因此這是代碼中的另一個問題。

為什么不簡單地使用css :focus選擇器來實現呢?

代替 :

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

采用:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM