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

如何使用JavaScript/jQuery拼接输入值时跳过空白输入项

实现方案

你可以采用配置化的方式重构拼接逻辑,自动跳过空输入项,同时满足前缀和对应输入项绑定的需求,修改后的完整代码如下:

JavaScript代码

// 统一配置所有输入项的选择器、前缀、后缀,后续调整格式只需修改该配置
const fieldConfig = [
  { selector: '#month2', prefix: '', suffix: ' ' },
  { selector: '#day2', prefix: '', suffix: ', ' },
  { selector: '#year2', prefix: '', suffix: ', P.L. ' },
  { selector: '#pl1a', prefix: '', suffix: '-' },
  { selector: '#pl2a', prefix: '', suffix: ', Div ' },
  { selector: '#div2', prefix: '', suffix: ', Title ' },
  { selector: '#title2', prefix: '', suffix: ', Subtitle ' },
  { selector: '#subtitle2', prefix: '', suffix: ', Ch ' },
  { selector: '#chapter2', prefix: '', suffix: ', Subch ' },
  { selector: '#subchapter2', prefix: '', suffix: ', § ' },
  { selector: '#section2', prefix: '', suffix: ', ' },
  { selector: '#stat1a', prefix: '', suffix: ' Stat. ' },
  { selector: '#stat2a', prefix: '', suffix: '' }
]

// 动态生成监听选择器,不用手动写一长串ID
const listenSelector = fieldConfig.map(item => item.selector).join(', ')

$(listenSelector).bind('keypress blur', function() {
  let result = 'Act '
  fieldConfig.forEach(item => {
    const value = $(item.selector).val().trim()
    // 仅非空的输入项参与拼接
    if (value) {
      result += item.prefix + value + item.suffix
    }
  })
  result += ', provides:'
  $('#input13').val(result)
})

逻辑说明

  • 所有输入项的格式规则统一维护在配置数组中,调整前缀、后缀不需要修改拼接逻辑,可维护性更高
  • 每次触发事件时会自动过滤空输入项,空项对应的前缀、后缀都不会出现在最终结果中,不会生成多余的逗号、空格,无需用户手动删除
  • 完全符合你要求的「固定文本归属到对应输入项前缀」的规则,比如Title 会和#title2的输入值绑定,#title2为空的话整段Title xxx都会被跳过

HTML代码不需要做任何修改,直接沿用你现有的代码即可正常运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 19:54:11