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

如何参数化jQuery的on()函数,实现仅对指定输入框做数字合法性校验

解决方案

你只需要在原有校验逻辑前新增判断规则,过滤出符合「父级label的title属性包含Valore」条件的输入框再执行校验即可,修改后的完整代码如下:

$(document).on('focusin', 'input', function () {
   $(this).data("oldvalue", this.value);
});
$(document).on('change', 'input', function () {
   // 新增判断:获取当前输入框所属表单组下的label,判断title是否包含Valore
   const $targetLabel = $(this).closest('.binf-form-group').find('label.binf-control-label');
   if (!$targetLabel.attr('title')?.includes('Valore')) {
       // 不符合条件直接终止后续校验逻辑
       return;
   }
   var $formGroup = $(this).closest('.binf-form-group');
   if ($.isNumeric(this.value)) {
       $formGroup.find('.binf-help-block').remove();
   } else {
       this.value = $(this).data("oldvalue");
       $('<div class="binf-help-block" role="alert" style="white-space: normal;margin-top: 8px;background: #fff;color: #df3324;font-size: 11px;line-height: 16px;border-radius: 2px;border-left: 2px solid #df3324;padding: 0 8px;box-shadow: 0 0 4px 0 rgba(0,0,0,.3);">This value must be a number.</div>').appendTo($formGroup).fadeOut(3000, function () { $(this).remove()});
   }
});

逻辑说明

  • 我们从当前触发change事件的输入框向上查找最近的.binf-form-group容器,再在容器内定位到对应的label标签
  • 判断label的title属性是否包含Valore,不匹配的输入框会直接跳过后续校验逻辑,不会触发错误提示
  • 如果你需要完全匹配title等于Valore,把includes方法换成=== 'Valore'即可
  • 如果运行环境不支持ES6可选链语法,可以把判断条件替换为兼容写法:
    const labelTitle = $targetLabel.attr('title');
    if (!labelTitle || labelTitle.indexOf('Valore') === -1) {
        return;
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 18:54:07