开发者

How to detect input types when binding event to parent

I am trying to bind an event to a parent instead of each child. I can successfully test for SELECT, TEXTAREA and A. How to I test for input[type='text']?

$('form').bind('focusin', function(e) {
    var target = e.target, // e.target grabs the node that triggered the event.
        $target = $(target);  // wraps the node in a jQuery object
    if (target.nodeName === 'SELECT' | target.nodeName === 'TEXTAREA' | target.nodeName === 'A') {开发者_JS百科
        alert('hi');
        // do stuff
    }
});


Note: from jQuery 1.7, use on() instead of delegate()


Using delegate() sounds the easiest and most fitting to me.

$('form').delegate('textarea, select, a, input[type="text"]', 'focusin', function () {
  alert('hu');
  //do stuff
});

Actually it does just what you asked for. The event itself is attached to form and checks whether the target matches the selector given.

Live Demo

No need to reinvent the wheel.


Might I recommend changing your code to something like this:

$('form').bind('focusin', function(e) {
    var $target = $(this); // wraps the node in a jQuery object
    if ($target.is('select') || $target.is('textarea') || $target.is('a') || $target.is('input[type="text"]') {
        alert('hi');
        // do stuff
    }
});

Alternatively, you can use the :input selector to select all form elements:

$target.is(':input')

http://api.jquery.com/input-selector/


if ($target.attr('type')=='text') {
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜