zoukankan      html  css  js  c++  java
  • click和blur冲突的问题

    昨天在前端群里讨论到一个问题,大家平时做表单验证的时候一般都有个input框和删除按钮,然后习惯性在失去焦点的时候去验证输入的内容是否正确,做验证,发请求等等。这个时候,那个点击删除按钮往往也就触发了input的失去焦点事件,这个该咋解决呢,经过研究有以下2种方法;

    1.

    给失去焦点的时间加上延迟时间,让blur时间在click事件后执行,这个方法固然能够解决问题,但是本人并不是很推荐,因为影响性能,不到最后不用这个方法;

    2.

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>DocumentDocument</title>
    </head>
    <body>
    <input type="text" id="box01"/><input type="button" id="box02" value="删除"/>
    <script src="http://ossweb-img.qq.com/images/js/jquery/jquery-1.7.2.min.js"></script>
    <script type="text/javascript">
        $("#box01").on("blur", function(event) {
            console.log(event.relatedTarget.id=='box02');
            console.log(event.relatedTarget==document.getElementById('box02'));
            console.log($('#box02')[0])
            console.log(event.relatedTarget==$('#box02')[0])
            if(event.relatedTarget==$('#box02')[0])
         {
          $(
    "#box01").val('');
          
    //return;
        }else{ alert(1) } })

    </script></body></html>

    就是以上代码了,用的是relatedTarget, w3c官网解释,事件属性返回与事件的目标节点相关的节点。意思就是我在失去焦点的时候,用

    relatedTarget判断一下失去焦点的时候是不是那个删除按钮触发的,如果是的话就直接清空input输入框,否则就去请求ajax.
    另外说一下,其实这个relatedTarget返回的是事件节点集合,所以我们在获取的时候要取它的第一个元素就好了,
    console.log(event.relatedTarget.id=='box02');
    console.log(event.relatedTarget==document.getElementById('box02')); console.log(event.relatedTarget==$('#box02')[0]);
    以上这三种方法都是可以的;

    但是方法二有个缺陷,我们要确保删除按钮是button 或者 input[type="button"]做的,我试过了,如果是其它标签,比如a,span,
     event.relatedTarget 是 null,因为其他元素获取不到焦点, 那么即便是因为点击 删除按钮 让 input 失去了焦点, 那也得不到 relatedTarget,
    反正2种方法各有利弊,自己权衡使用吧。
    以上仅代表个人观点,如有错误还望指正。
    
    
  • 相关阅读:
    nginx Server names
    ES6--变量的声明及解构赋值
    Android ListView and Tips.
    Eclipse自己定义keystore
    POJ 1129 Channel Allocation(DFS)
    机器学习笔记十三:Ensemble思想(上)
    设计模式——享元模式具体解释
    老猪带你玩转自定义控件三——sai大神带我实现ios 8 时间滚轮控件
    老猪带你玩转android自定义控件二——自定义索引栏listview
    android动手写控件系列——老猪叫你写相机
  • 原文地址:https://www.cnblogs.com/liujingjing/p/5710362.html
Copyright © 2011-2022 走看看