最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Event bubbling and the onblur event - Stack Overflow

programmeradmin2浏览0评论

I'm writing a form validation script and would like to validate a given field when its onblur event fires. I would also like to use event bubbling so i don't have to attach an onblur event to each individual form field. Unfortunately, the onblur event doesn't bubble. Just wondering if anyone knows of an elegant solution that can produce the same effect.

I'm writing a form validation script and would like to validate a given field when its onblur event fires. I would also like to use event bubbling so i don't have to attach an onblur event to each individual form field. Unfortunately, the onblur event doesn't bubble. Just wondering if anyone knows of an elegant solution that can produce the same effect.

Share Improve this question asked Oct 6, 2009 at 13:50 Stephen SorensenStephen Sorensen 11.9k13 gold badges35 silver badges47 bronze badges 2
  • each form field is has a different validate function or it's the same for all fields? – Peter Commented Oct 6, 2009 at 13:54
  • they all use the same callback function. the callback function looks for certain classes on the html element that tell it how to validate ( like "required" or "integer" ) – Stephen Sorensen Commented Oct 6, 2009 at 14:02
Add a comment  | 

4 Answers 4

Reset to default 9

You're going to need to use event capturing (as opposed to bubbling) for standards-compliant browsers and focusout for 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;

    // ...
}

See http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html for the juicy details

use 'Focusout' event as it has Bubble up effect..thanks.

ppk has a technique for this, including the necessary workarounds for IE: http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html

aa, you can simply add the onblur event on the form, and will call the validation every time you change focus on any of the elements inside it

发布评论

评论列表(0)

  1. 暂无评论