jQuery 输入文本框的悬停事件不起作用

jQuery hover event for input textbox is not working

我有一个包含 html 和 jQuery 代码的网页,如下所示。我已经订阅了 ID 为 firstname 的输入文本框的悬停事件,但它永远不会在悬停在文本框上时触发。我已将此事件代码放入文档就绪事件中。

这个问题的演示在这个 URL: demo sample

问题:下面的 jQuery 订阅悬停事件的代码有什么问题?我的目标是在文本框悬停时应用 highlight class。

Html代码

<style>
   .highlight {
   background-color: yellow;
   border: 1px red solid;
   }
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
   <tr class='class1'>
      <td>
         <!--some content here-->
         I am a td element
      </td>
      <td>
         <table>
            <tr>
               <td>
                  First Name 
               </td>
               <td>
                  <input type='text' id='firstname'>  
               </td>
            </tr>
            <tr>
               <td>
                  Last Name 
               </td>
               <td>
                  <input type='text' id='lastname'>
               </td>
            </tr>
         </table>
      </td>
   </tr>
</table>
<script>
$(document).ready(function() {
    var firstName = $('#firstname');
    firstName.on('hover', function() {
        if($(this).hasClass('highlight') === false) {
            $(this).addClass('highlight');
        } 
    });
});
</script>

更新

根据回答,我更新了演示示例。您可以在此 URL 查看修改后的示例:modified demo sample that is working.

在这个修改后的示例中,我只是按照 DinoMyte 建议的方法,即在处理悬停 effect/event in jquery 时使用以下格式:jQueryObject.hover(on function when hovering starts, off function when hovering out)

hover事件可以绑定,不能委托。您需要更换

firstName.on('hover', function() {

用这个 :

firstName.hover(function() {

工作:https://jsfiddle.net/DinoMyte/jmt4bmtm/

如果您希望委托该事件,则需要使用 mouseover 的替代方法。

更新:如果您希望在悬停时触发开关效果,您可以执行以下操作:

 $(document).ready(function() {
       var firstName = $('#firstname');
       firstName.hover(function() 
       {
         if($(this).hasClass('highlight') === false) 
         $(this).addClass('highlight');
       }, 
       function() 
       {
         $(this).removeClass('highlight');
      }
   );
});

工作示例:https://jsfiddle.net/DinoMyte/jmt4bmtm/1/

如果委派对于您的解决方案真的很重要,您可以使用以下使用 mouse 事件的方法。

 $(document).ready(function() {
       var firstName = $('#firstname');
       firstName.on("mouseover",function() 
       {
         if($(this).hasClass('highlight') === false) 
         $(this).addClass('highlight');
       }).on("mouseleave",function()
       {
         $(this).removeClass('highlight');
       });
});

工作示例:https://jsfiddle.net/DinoMyte/jmt4bmtm/3/

您可以像这样绑定 hover 事件:

$(document).ready(function() {
  var firstName = $('#firstname');
  firstName.hover(function() {
    $(this).addClass('highlight');
  }, function() {
    $(this).removeClass('highlight');
  });
});

https://jsfiddle.net/av38Lvqs/