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

jQuery绑定多个输入框,如何获取变更后的新值及对应输入项?

解决方法:获取触发变更的输入框及新值

当然可以轻松实现这个需求!你之前只打印事件对象e没拿到有效信息,是因为需要从事件上下文里提取目标元素的属性。这里有两种简单的方式:

方式一:使用this关键字(推荐)

在jQuery的事件处理函数中,this直接指向触发事件的DOM输入框元素,你可以直接获取它的name和value属性:

$("input[name=hoehe], input[name=bodenfreiheit], input[name=breite], input[name=anzahl], input[name=laenge], input[name=pfosten_anzahl]").bind('keyup mouseup', function (e) {
    // 获取触发事件的输入框名称
    const inputName = this.name;
    // 获取输入框的最新值
    const newValue = this.value;

    console.log(`触发变更的输入框:${inputName}`);
    console.log(`变更后的新值:${newValue}`);
});

方式二:使用事件对象的target属性

如果你更习惯通过事件对象e来获取元素,e.target也能拿到触发事件的DOM元素,效果和this一致:

$("input[name=hoehe], input[name=bodenfreiheit], input[name=breite], input[name=anzahl], input[name=laenge], input[name=pfosten_anzahl]").bind('keyup mouseup', function (e) {
    const inputElement = e.target;
    const inputName = inputElement.name;
    const newValue = inputElement.value;

    console.log(`输入框 ${inputName} 已更新,新值:${newValue}`);
});

额外建议:替换过时的bind()方法

另外要提醒一下,jQuery的bind()方法已经被标记为过时,现在官方推荐使用on()方法来绑定事件,用法几乎一致,兼容性更好:

$("input[name=hoehe], input[name=bodenfreiheit], input[name=breite], input[name=anzahl], input[name=laenge], input[name=pfosten_anzahl]").on('keyup mouseup', function (e) {
    const inputName = this.name;
    const newValue = this.value;
    console.log(`输入框 ${inputName} 的最新值:${newValue}`);
});

这样你就能清晰地知道哪个输入框发生了变更,以及它的最新内容啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:29:58