事件冒泡和onblur事件

6

我正在编写一个表单验证脚本,希望在字段失去焦点时验证给定的字段。我还想使用事件冒泡,这样我就不必为每个单独的表单字段附加onblur事件。不幸的是,onblur事件不会冒泡。不知道是否有人知道可以产生相同效果的优雅解决方案。


每个表单字段都有不同的验证函数,还是所有字段都使用相同的函数? - Peter
它们都使用相同的回调函数。回调函数查找HTML元素上的特定类,告诉它如何验证(例如“required”或“integer”)。 - Stephen Sorensen
4个回答

9

对于符合标准的浏览器,您需要使用事件捕获(而不是冒泡),对于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


7
使用“Focusout”事件,因为它具有冒泡效应。谢谢。

2

-2

嗯,你可以在表单上简单地添加onblur事件,这样每次你在其中任何一个元素上改变焦点时都会调用验证。


1
你确定吗?我原本不认为表单会出现模糊,特别是因为它首先就不能获取焦点。 - nickf

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接