【问题标题】:Event bubbling and the onblur event事件冒泡和 onblur 事件
【发布时间】:2009-10-06 13:50:11
【问题描述】:

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

【问题讨论】:

  • 每个表单字段都有不同的验证功能还是所有字段都相同?
  • 它们都使用相同的回调函数。回调函数在 html 元素上查找某些告诉它如何验证的类(如“必需”或“整数”)

标签: javascript event-bubbling onblur


【解决方案1】:

您将需要为符合标准的浏览器使用事件捕获(而不是冒泡),为 IE 使用 focusout:

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

【讨论】:

    【解决方案2】:

    使用 'Focusout' 事件,因为它具有 Bubble up 效果..谢谢。

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

        要对onblur事件使用冒泡,那么你可以使用addEventListener()并将useCapture参数设置为false。像这样:

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

        Firefox 51 及更低版本不支持onfocusout 事件。所以不要使用onfocusout 代替onblur 事件。

        【讨论】:

          【解决方案5】:

          aa,您可以简单地在表单上添加 onblur 事件,并且每次您将焦点更改为其中的任何元素时都会调用验证

          【讨论】:

          • 你确定吗?我根本没想到表格会变得模糊,尤其是因为它一开始就没有焦点。
          猜你喜欢
          • 2012-02-09
          • 2011-06-11
          • 1970-01-01
          • 2014-03-07
          • 2011-10-20
          • 2011-08-23
          • 1970-01-01
          • 2021-08-14
          • 1970-01-01
          相关资源
          最近更新 更多