如何在多组name为数组形式的输入框上使用jQuery each函数?
用jQuery each处理你的publisher文本框
嘿,我来帮你搞定这个jQuery each的用法~根据你的需求,分几种常见场景给你示例:
场景1:遍历所有三类文本框(逐个处理每个输入框)
如果想一次性处理所有publishername、publisherlocation、publisheremail这三个类的文本框,可以用多选择器组合,然后通过each遍历:
// 选择所有目标文本框,用逗号分隔多个选择器 $('.publishername, .publisherlocation, .publisheremail').each(function(index, element) { // $(this) 指向当前正在遍历的文本框jQuery对象 const inputValue = $(this).val().trim(); const inputName = $(this).attr('name'); // 示例:打印每个输入框的信息 console.log(`第${index + 1}个输入框 | name: ${inputName} | 值: ${inputValue}`); // 这里可以添加你的业务逻辑,比如空值验证 if (!inputValue) { $(this).addClass('border-danger'); // 给空输入框加红色边框 } else { $(this).removeClass('border-danger'); } });
场景2:按组遍历(如果文本框是按“发布者”分组排列的)
假设你的HTML是按每组一个发布者信息来组织的(比如放在同一个容器里),像这样:
<div class="publisher-row"> <input type="text" name="publishername[]" class="form-control publishername"> <input type="text" name="publisherlocation[]" class="form-control publisherlocation"> <input type="text" name="publisheremail[]" class="form-control publisheremail"> </div> <div class="publisher-row"> <!-- 第二个发布者的三个输入框 --> </div>
这种情况下,你可以先遍历每个分组容器,再在组内获取对应的输入框:
// 遍历每个发布者分组 $('.publisher-row').each(function(groupIndex) { const $currentGroup = $(this); // 从当前组中获取三个输入框的值 const publisherName = $currentGroup.find('.publishername').val().trim(); const publisherLocation = $currentGroup.find('.publisherlocation').val().trim(); const publisherEmail = $currentGroup.find('.publisheremail').val().trim(); // 示例:打印整组信息 console.log(`第${groupIndex + 1}组发布者 | 名称: ${publisherName} | 地点: ${publisherLocation} | 邮箱: ${publisherEmail}`); // 示例:验证整组是否填写完整 if (publisherName && publisherLocation && publisherEmail) { $currentGroup.addClass('bg-success-subtle'); // 给完整的组加浅绿背景 } else { $currentGroup.addClass('bg-warning-subtle'); // 给不完整的组加浅黄背景 } });
场景3:单独遍历某一类文本框
如果只想处理某一类,比如所有publishername的输入框,写法更简单:
$('.publishername').each(function() { const nameValue = $(this).val().trim(); // 针对每个名称输入框做处理,比如格式验证 if (nameValue.length < 2) { $(this).next('.error-message').text('名称不能少于2个字符'); } });
小提示
在each函数里,$(this)会自动指向当前遍历到的DOM元素(转成了jQuery对象);你也可以用第二个参数element获取原生DOM元素,比如$(element)和$(this)效果完全一样。
内容的提问来源于stack exchange,提问作者New to Everything
相关产品推荐
相关产品推荐

