You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用jQuery on事件处理器时,无法获取input元素type属性怎么办?

问题原因

你把input事件绑定在了<form>元素上,代码里的this指向的是form标签,而form本身并没有type属性,所以会弹出undefined。

解决方法

有两种可行的修正方式:

方式一:直接绑定事件到input元素

把事件委托的目标改为form内的input元素,这样this就会指向触发事件的input:

$(document).on('input', 'form[name="filter"] input', function () { 
     alert(this.type); 
});

方式二:通过事件对象获取触发元素

如果坚持绑定事件在form上,可以通过事件参数e的target属性拿到实际触发事件的input元素:

$(document).on('input', 'form[name="filter"]', function (e) { 
     // 先判断触发元素是input,避免其他元素触发的情况
     if(e.target.tagName === 'INPUT'){
         alert(e.target.type); 
     }
});

内容的提问来源于stack exchange,提问作者Jack Maessen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 07:02:35