当失去焦点时,可以阻止jQuery焦点退出吗? [英] Can you stop the jQuery focusout from firing when losing focus?

查看:69
本文介绍了当失去焦点时,可以阻止jQuery焦点退出吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个输入框,当它失去焦点时,我想保存它的值.

I've got an input box that I want to have save its value when it loses focus.

非常简单的东西,我可以通过jQuery的focusout事件来完成.

Pretty straightforward stuff and I'm able to get that done via jQuery's focusout event.

但是,问题是,当用户单击输入框旁边的"X"图标时,我不想触发focusout事件(如下所示的示例)

The problem however, is that I want to NOT fire the focusout event when the user clicks on an "X" icon next to the input box (example shown below)

因此,当用户跳出此输入框或在框外单击或单击绿色复选框时,应触发focusout事件...但是,如果用户单击红色的"X",则不应触发focusout.

So when the user tabs out of this input box, or clicks outside of the box or they click the green checkbox it should fire the focusout event... but if they click the red "X", it should NOT fire the focusout.

这可能与JavaScript/jQuery有关吗?

Is this possible to do with JavaScript / jQuery?

某些人建议使用event.relatedTarget,但似乎返回的是null.为了清楚起见,我将包含我的代码:

Some of you have recommended using event.relatedTarget, but it seems like that's returning null. I'll include my code in question for clarity:

  // This is the cancel button with the red X
  $("body").on("click", "span[id*='Cancel']", function(e)
  {
    showLabel($(this));
  });

  // this is the code to trigger the blur / focusout event
  // trouble is that the "e.relatedTarget" is null
  $("body").on("focusout", "input, textarea", function (e) {
    if($(e.relatedTarget).is("span[id*='Cancel']")){
      return false;
    }

    $(this).siblings("span[id*='OK']").trigger("click");
    return false;
  });

这是我在JS中调试它的屏幕截图(您会看到$(e.relatedTarget)选择器不返回任何内容):

Here's a screen grab of me debugging this in JS (you'll see that the $(e.relatedTarget) selector returns nothing):

推荐答案

您必须像这样使用relatedTarget:

$(document).ready(function(){

    $(".btn").on("focusout",function(e){

        if($(e.relatedTarget).hasClass("red")) {
             alert("You clicked on X button");
        }

        else {

            alert("Fire Focus out")
        }

    })
   })

最终代码:

<!DOCTYPE html>
<html>
    <head>
        <style>
            .gr {
                color: green;
            }
            .red {
                color: red;
            }
        </style>
    </head>
    <body>
       <input type="text" class="btn"><button class="gr">Ok</button><button class="red">X</button>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script>
    $(document).ready(function(){

        $(".btn").on("focusout",function(e){

            if($(e.relatedTarget).hasClass("red")) {
                 alert("You clicked on X button");
            }

            else {

                alert("Fire Focus out")
            }

        })
    })
    </script>
    </body>  
</html>
        

这篇关于当失去焦点时,可以阻止jQuery焦点退出吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆