如何在将事件绑定到父事件时检测输入类型

How to detect input types when binding event to parent

本文关键字:事件 检测 输入 类型 绑定      更新时间:2023-09-26

我试图将事件绑定到父节点而不是每个子节点。我可以成功地测试SELECT, TEXTAREA和A.我如何测试输入[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') {
        alert('hi');
        // do stuff
    }
});

注意:从jQuery 1.7开始,使用on()代替delegate()


使用delegate()听起来最简单,最适合我。

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

实际上它正是你所要求的。事件本身附加到form并检查target是否与给定的选择器匹配。

现场演示

不需要重新发明轮子

我建议你把代码改成这样:

$('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
    }
});

或者,您可以使用:input选择器来选择所有表单元素:

$target.is(':input')
http://api.jquery.com/input-selector/

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