You need to enable JavaScript to run this app. 如何使用jQuery或JavaScript按二级键location选择pref[*][location][]格式的input元素
优惠活动
大模型
产品
解决方案
定价
更多

如何使用jQuery或JavaScript按二级键location选择pref[*][location][]格式的input元素

匹配目标 input 元素的实现方案

jQuery 实现

直接靠CSS属性选择器组合就能完成精准匹配,不用额外写遍历逻辑,性能最优:

const targetInputs = $('input[name^="pref["][name$="][location][]"]');

匹配逻辑拆解:

  • name^="pref[" 条件:筛出所有name以pref[开头的元素,从根源上排除那个独立的、name直接为location的input
  • name$="][location][]" 条件:在这批元素里,进一步找name以][location][]结尾的项,刚好对应要求的“二级键为location、末尾带数组传值后缀[]”的结构
  • 两个条件中间夹的任意内容,就是我们完全不用关心的pref后第一层索引值,不管是数字1/2/3还是其他自定义值,都能正常匹配,不会因为索引变了漏选

如果遇到很奇葩的自定义name结构,担心匹配不准,可以用正则过滤的版本兜底:

const targetInputs = $('input').filter(function() {
  // 正则严格校验完整name结构
  return /^pref\[[^\]]+\]\[location\]\[\]$/.test(this.name);
});

正则的好处是匹配逻辑更严谨:

  • 从字符串开头就校验必须是pref[,不会和其他同前缀但结构不符的元素混淆
  • [^\]]+ 精准匹配第一层括号里的非空内容,不会出现跨括号的匹配错位
  • 最后校验必须以][location][]收尾,确保二级键和数组后缀完全符合要求

原生 JavaScript 实现

对应上面的jQuery方案,原生有两种实现方式:

  1. 直接用querySelectorAll跑同一套属性选择器,性能最高:
    const targetInputs = document.querySelectorAll('input[name^="pref["][name$="][location][]"]');
    
  2. 对匹配精度要求高的话,用正则遍历所有input筛选:
    const targetInputs = Array.from(document.querySelectorAll('input')).filter(input => {
      return /^pref\[[^\]]+\]\[location\]\[\]$/.test(input.name);
    });
    

拿你给的示例结构跑一遍验证,上面的代码最终会选中所有值为get_this、get_this_too的4个目标元素,自动排除其他term、other类的input,以及那个独立命名为location的input,完全符合筛选规则。

内容的提问来源于stack exchange,提问作者yhd.leung

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.27 10:15:03