繁体   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