如何遍历数组获取jQuery属性以实现值为null的对应字段自动隐藏
问题原因
你使用for...in遍历数组时,变量x拿到的是数组的索引字符串("0"、"1"、"2"),并不是数组内存储的子元素。你写的x[0]实际是取索引字符串的第一个字符,永远不可能等于null,所以隐藏逻辑永远不会触发。
修复方案
直接修改现有代码
改用for...of直接遍历数组元素即可:
const campos_poliza = [ [json[0].incendio_edificio, $("#dIncendio_edificio")], [json[0].hvct_edificio, $("#dHvct_edificio")], [json[0].granizo_edificio, $("#dGranizo_edificio")], ]; for (const item of campos_poliza) { if (item[0] == null) { item[1].parent().parent().hide(); } }
如果需要兼容不支持for...of的旧环境,可以用普通for循环:
for (let i = 0; i < campos_poliza.length; i++) { const item = campos_poliza[i]; if (item[0] == null) { item[1].parent().parent().hide(); } }
更精简的优化写法
你可以只存储字段名,后续新增字段只需要修改数组即可,代码冗余度更低:
// 后续新增判断字段只需要往该数组加字段名即可 const fieldList = ['incendio_edificio', 'hvct_edificio', 'granizo_edificio']; fieldList.forEach(field => { if (json[0][field] == null) { // 用closest('.row')替代连续parent,DOM层级调整也不会失效,更稳定 $(`#d${field}`).closest('.row').hide(); } })
内容的提问来源于stack exchange,提问作者user5482212
相关产品推荐
相关产品推荐

