我正在编写一个表单验证脚本,希望在字段失去焦点时验证给定的字段。我还想使用事件冒泡,这样我就不必为每个单独的表单字段附加onblur事件。不幸的是,onblur事件不会冒泡。不知道是否有人知道可以产生相同效果的优雅解决方案。
我正在编写一个表单验证脚本,希望在字段失去焦点时验证给定的字段。我还想使用事件冒泡,这样我就不必为每个单独的表单字段附加onblur事件。不幸的是,onblur事件不会冒泡。不知道是否有人知道可以产生相同效果的优雅解决方案。
对于符合标准的浏览器,您需要使用事件捕获(而不是冒泡),对于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
ppk有一种技术可以做到这一点,包括IE所需的解决方法:http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html
嗯,你可以在表单上简单地添加onblur事件,这样每次你在其中任何一个元素上改变焦点时都会调用验证。