jQuery each函数报错:合并多组input遍历语句时出现不可识别错误
解决jQuery each遍历多组input的语法错误问题
嘿,我一眼就发现你遇到的问题根源了——你的jQuery选择器写得有语法错误,这才导致浏览器抛出“不可识别”的错误!
问题出在哪?
你写的选择器片段存在两个关键语法问题:
$('input[name="publishername[]" ,input[name="publisherlocation[]" , inp...
- 每个
input[name="xxx[]"]选择器都没有正确闭合引号和方括号,比如第一个选择器只写了input[name="publishername[]",缺了闭合的"] - 错误地在逗号分隔的选择器里嵌套了
input[name="..."],正确的写法应该是每个选择器都是独立完整的,用逗号直接分隔。
修正后的正确写法
先把选择器修正成合法格式,再进行each遍历:
完整的jQuery代码示例
// 正确的选择器:三个独立的input选择器用逗号分隔 $('input[name="publishername[]"], input[name="publisherlocation[]"], input[name="publisheremail[]"]').each(function(index, element) { // 在这里编写你的遍历逻辑,比如获取输入值或操作元素 const inputValue = $(this).val(); const inputName = $(this).attr('name'); console.log(`输入框${inputName}的值:${inputValue}`); });
对应的HTML结构(确认无误)
<input type="text" name="publishername[]" class="form-control publishername" placeholder="出版社名称"> <input type="text" name="publisherlocation[]" class="form-control publisherlocation" placeholder="出版社地址"> <input type="text" name="publisheremail[]" class="form-control publisheremail" placeholder="出版社邮箱">
额外优化建议
其实你可以利用这些input的类名简化选择器,代码更易读也不容易出错:
// 用类名组合选择器,和上面的效果完全一致 $('.publishername, .publisherlocation, .publisheremail').each(function(index, element) { // 你的遍历逻辑 });
这样修改后,浏览器就能正确识别选择器,each遍历也能正常工作啦!
内容的提问来源于stack exchange,提问作者New to Everything
相关产品推荐
相关产品推荐

