代码之家  ›  专栏  ›  技术社区  ›  Stephen Sorensen

事件冒泡和onblur事件

  •  3
  • Stephen Sorensen  · 技术社区  · 15 年前

    我正在编写一个表单验证脚本,并希望在给定字段的onblur事件触发时对其进行验证。我还希望使用事件冒泡,这样就不必将onblur事件附加到每个单独的表单字段。不幸的是,onblur事件不会冒泡。只是想知道是否有人知道一个优雅的解决方案可以产生同样的效果。

    5 回复  |  直到 8 年前
        1
  •  2
  •   NickFitz    15 年前

    PPK对此有一种技术,包括IE的必要解决方法: http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html

        2
  •  9
  •   Crescent Fresh    15 年前

    对于符合标准的浏览器和 focusout IE:

    if (myForm.addEventListener) {
        // Standards browsers can use event Capturing. NOTE: capturing 
        // is triggered by virtue of setting the last parameter to true
        myForm.addEventListener('blur', validationFunction, true);
    }
    else {
        // IE can use its proprietary focusout event, which 
        // bubbles in the way you wish blur to:
        myForm.onfocusout = validationFunction;
    }
    
    // And of course detect the element that blurred in your handler:
    function validationFunction(e) {
        var target = e ? e.target : window.event.srcElement;
    
        // ...
    }
    

    参见 http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html 关于多汁的细节

        3
  •  3
  •   Umesh K.    12 年前

    使用 聚焦 “事件本身具有气泡效应……谢谢。

        4
  •  0
  •   Iman Sedighi    8 年前

    使用气泡 onblur 事件,然后可以使用addEventListener()并将useCapture参数设置为 . 这样地:

    yourFormInput.addEventListener('blur', yourFunction, false);
    

    火狐51及以下版本不支持 onfocusout 事件。所以不要使用 聚焦 而不是 事件 事件。

        5
  •  -2
  •   TheBrain    15 年前

    aa,您可以简单地将onblur事件添加到表单中,并在每次更改时调用验证,重点放在表单中的任何元素上。