Using jQuery focus and blur to show and hide a mes

2019-07-12 03:33发布

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>

2条回答
混吃等死
2楼-- · 2019-07-12 03:48

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>
查看更多
Lonely孤独者°
3楼-- · 2019-07-12 04:09

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();        
          });
});
查看更多
登录 后发表回答