为什么我在 jquery 中的 focus() 不起作用

Why my focus() in jquery not working?

本文关键字:不起作用 focus 中的 jquery 为什么      更新时间:2023-09-26

我想在焦点上更改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");
  });
});

我做错了什么?

而不是 :

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

用:

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

这是因为您只能将.focus()应用于有限数量的元素(链接,表单输入(。

来自jQuery文档:

焦点

事件在元素获得焦点时发送到该元素。此事件 隐式适用于一组有限的元素,例如表单 元素 (、 等(和链接 ((。最近 浏览器版本,事件可以扩展为包含所有元素 类型,方法是显式设置元素的 TabIndex 属性。一 元素可以通过键盘命令(例如 Tab 键(获得焦点,或者 通过鼠标单击元素。

在这里,您尝试将其应用于<td>标签。

此外,您的<input>不是.TD的孩子,因此这是您的代码中的另一个问题。

为什么不简单地使用css :focus选择器来实现这一点呢?