jQuery - 检测用户何时单击输入类型文本字段的 OUT

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4585890/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:31:32  来源:igfitidea点击:

jQuery - Detecting when a user clicks OUT of an input type Text Field

jquery

提问by AnApprentice

I want to detecting when a user clicks OUT of an input type Text Field, not in.

我想检测用户何时单击输入类型文本字段的输出,而不是输入。

Here's what I have but both events are firing on click inside (focus):

这是我所拥有的,但两个事件都在点击内部(焦点)时触发:

<input id="title" val="hello" />

$("#title").focusout(function() {
    console.log('inside');
}).blur(function() {
    console.log('outside');
});

回答by hunter

You can bind your focusand blurevent like so:

您可以像这样绑定您的focusblur事件:

<input id="title" val="hello" type="text" />

$("#title").focus(function() {
    console.log('in');
}).blur(function() {
    console.log('out');
});

focusoutisn't necessary since it's geared toward event bubbling for child elements: http://api.jquery.com/focusout/

focusout没有必要,因为它面向子元素的事件冒泡:http: //api.jquery.com/focusout/

回答by jAndy

You could write a little plugin, like

你可以写一个小插件,比如

(function($){
  $.fn.outside = function(ename, cb){
      return this.each(function(){
          var $this = $(this),
              self = this;

          $(document).bind(ename, function tempo(e){
              if(e.target !== self && !$.contains(self, e.target)){
                  cb.apply(self, [e]);
                  if(!self.parentNode) $(document.body).unbind(ename, tempo);
              }
          });
      });
  };
}(jQuery));

..and use it like:

..并使用它:

$('#title').outside('click', function(e) {
    console.log('outside');
});

Example: http://www.jsfiddle.net/tGnun/

示例:http: //www.jsfiddle.net/tGnun/

回答by Aaron Hathaway

It's looking like focusout()and blur()are both triggering when you click outside of the text. Try using focus()instead. Check it out here.

当您在文本外部单击时,它看起来像focusout()并且blur()都被触发。尝试使用focus()。检查它在这里

回答by DwB

I'm not 100% sure that this is what you want, but here is a stab at it:

我不是 100% 确定这是你想要的,但这里有一个刺:

<html>
<head>
<title>Example</title>
<script src="jquery-1.4.3.js" type="text/javascript"></script>
</head>
<body id="body">
<script>
    $("document").ready( function() 
    {   $("#body").click( function()
        { alert("body"); } );
        $("#input").click( function(event)
        { alert("input"); event.stopPropagation(); } );
    } );
</script>
<h2>input below</h2>
<input id="input" type="text"/>
</body>
</html>