Using jQuery focus and blur to show and hide a mes

2019-07-12 03:22发布

问题:

I am clicking to set focus on a textbox, and once I have set focus I am trying to display a simple message. Then on blur that message disappears.

Here is my code: If I click on the textbox it displays the message but if I click the button it doesn't set focus as I thought it would.

<script>
$(document).ready(function(){    
  $("#clicker").click(function(){        
    $("#T1").focus(function(){            
      $("#myFocus").show();        
    });     
  });        

  $("#T1").blur(function(){        
    $("#myFocus").hide();    
  });
});
</script>

<body>
<div id="clicker" style="cursor:pointer; border:1px solid black; width:70px;">
  Click here!
</div>
<br /><br />
<input id="T1" name="Textbox" type="text" />
<div id="myFocus" style="display: none;">focused!</div>

回答1:

You need to trigger the focus event, instead of defining it. Try this instead:

<script>
$(function() { // Shorthand for $(document).ready(function() {
      $('#clicker').click(function() {
            $('#T1').focus(); // Trigger focus
      });

      $('#T1').focus(function() { // Define focus handler
            $('#myFocus').show();
      }).blur(function() {
            $('#myFocus').hide();
      });
});
</script>


回答2:

The problem is here:

$("#T1").focus(function(){            
      $("#myFocus").show();        
});

You should trigger the event with focus() not attach a callback with focus(function(){...}

Fixed code:

$(document).ready(function(){    
  $("#clicker").click(function(){        
        $('#T1').focus();
  });        

  $("#T1").blur(function(){        
      $("#myFocus").hide();    
  })     .focus(funcion(){
              $("#myFocus").show();        
          });
});