简体   繁体   English

使用jQuery焦点和模糊显示和隐藏消息

[英]Using jQuery focus and blur to show and hide a message

I am clicking to set focus on a textbox , and once I have set focus I am trying to display a simple message. 我单击以将focus设置在textbox ,一旦设置了焦点,我将尝试显示一条简单的消息。 Then on blur that message disappears. 然后在blur该消息消失。

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. 这是我的代码:如果单击textbox它将显示消息,但是如果单击按钮,则不会按我预期的那样设置焦点。

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

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>

The problem is here: 问题在这里:

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

You should trigger the event with focus() not attach a callback with focus(function(){...} 您应该使用focus()触发事件,而不要使用focus(function(){...}附加回调

Fixed code: 固定代码:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM